Search code examples
phpregexurlslug

str_replace


Current code only replace the spaces to dash (-)

$url = str_replace(' ','-',$url);

I want only letters, numbers and dash (-) allowed on the URL.

Let me know the tricks.


Solution

  • Do you want this for generating slug?

    Then you can do something like this:

    $slugified = preg_replace('/[^-a-z0-9]+/i', '-', strtolower(trim($url)));
    

    It will strip leading and trailing whitespace first, convert the string to lowercase, then replace all non-word characters (not a-z, 0-9 or -) with a single -

    A    Beautiful *# Day will become a-beautiful-day

    Remove strtolower() if you don't mind uppercase letters in the slug.