Search code examples
phpstringreplacesanitizationslugify

Sanitize/Slugify a string by replacing non-alphanumeric and non-hyphen characters


I am getting strings from a database and then using the strings to build a URL.

My issue is, some of the strings will have characters like < > & { } * general special characters, but the string may also have strings in.

How would I replace the spaces with dashes and totally remove and special characters from the strings?


Solution

  • With str_replace:

    $str = str_replace(array(' ', '<', '>', '&', '{', '}', '*'), array('-'), $str);
    

    Note:

    If replace has fewer values than search, then an empty string is used for the rest of replacement values.