Robert Andrews Robert Andrews - 16 days ago 7
PHP Question

PHP to convert string to slug

What is the best way to convert a string of text to a slug? Meaning:


  • alpha allowed, convert to lowercase

  • numbers are allowed

  • spaces should be eliminated, not converted to dash ("-")

  • accented characters replaced by equivalent standard alpha

  • no other characters allowed, should be stripped out



I have found plenty of code online, but it all tends to convert spaces to dashes, which I do not want to do.

I am also interested optionally in varying the conversion, wherein:


  • ampersand ("&") should be replaced by the string "and"



And also a variant wherein:


  • Don't bother converting accented characters to equivalent standard alpha


Answer

Here is a modified function that I originally found here (http://cubiq.org/the-perfect-php-clean-url-generator). you can pass '' as the delimiter to not use '-'.

public static function createSlug($str, $delimiter = '-'){

    $slug = strtolower(trim(preg_replace('/[\s-]+/', $delimiter, preg_replace('/[^A-Za-z0-9-]+/', $delimiter, preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', iconv('UTF-8', 'ASCII//TRANSLIT', $str))))), $delimiter));
    return $slug;

} 
Comments