81

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

I need to make it all lowercase, remove all special characters and replace spaces with dashes.

Rob
  • 6,304
  • 24
  • 83
  • 189

3 Answers3

265

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 fine :)

rorypicko
  • 4,194
  • 3
  • 26
  • 43
  • 1
    Thank you. It's a nice simple function, It would be nice to be extended to strip out certain seo-unfriendly keywords like 'the' & 'and'. – rorypicko Jul 10 '13 at 14:49
  • 5
    [This question](http://stackoverflow.com/questions/9734970) suggests it's not worth stripping out 'stop' words; I created a [gist](https://gist.github.com/chrisveness/7c34a3f18938f33d513c) which adds accented character handling to rory's solution. – ChrisV Jun 17 '14 at 07:31
  • how can i remove the first and last space without `-` symbol.? – Kvvaradha Jun 03 '16 at 10:53
  • @Kvvaradha Paste the following line as the first line in the function `$string = trim($string);` and that will solve your issue. – Devner Dec 04 '16 at 16:28
  • how to use this – AjithChadda Jun 02 '18 at 05:59
  • @AjithChadda `seoUrl("noner SEO @@@ STrings vs_£(----");` = 'noner-SEO-STrings-vs' – rorypicko Jun 05 '18 at 16:48
  • @rorypicko To strip out seo-unfriendly keywords you just need to add in the following three lines: `$find = array('the","and"); //You can also enter any other keywords you would like to remove here. $replace = array(""); $string = str_replace($find,$replace,$string);` – Angeliss44 Mar 08 '19 at 23:58
  • Thanks straight anwer! – Eme Hado Jan 24 '20 at 11:50
9

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;
}
NoLifeKing
  • 1,909
  • 13
  • 27
9

Yop, and if you want to handle any special characters you'll need to declare them in the pattern, otherwise they may get flushed out. You may do it that way:

strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $string)));
Pierre Voisin
  • 661
  • 9
  • 11