Change php variable, replace white spaces with dashed

How can I convert a PHP variable from "My company and my name" to "my-company-my-name"?

I need to do everything lowercase, remove all special characters and replace the dashes with spaces.

+55
php
Jul 04 2018-12-12T00:
source share
3 answers

This function will create an SEO friendly string.

function seoUrl($string) { //Lower case everything $string = strtolower($string); //Make alphanumeric (removes all other characters) $string = preg_replace("/[^a-z0-9_\s-]/", "", $string); //Clean up multiple dashes or whitespaces $string = preg_replace("/[\s-]+/", " ", $string); //Convert whitespaces and underscore to dash $string = preg_replace("/[\s_]/", "-", $string); return $string; } 

should be good :)

+193
Jul 04 2018-12-12T00:
source share

Replacing specific characters: http://se.php.net/manual/en/function.str-replace.php

Example:

 function replaceAll($text) { $text = strtolower(htmlentities($text)); $text = str_replace(get_html_translation_table(), "-", $text); $text = str_replace(" ", "-", $text); $text = preg_replace("/[-]+/i", "-", $text); return $text; } 
+8
Jul 04 2018-12-14T00:
source share

Yop, and if you want to handle any special characters, you need to declare them in the template, otherwise they can be reset. You can do it like this:

 strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wÑéíóú]/', '-', $string))); 
+6
Jul 04 '12 at 14:33
source share



All Articles