Search code examples
phppreg-replacesubstr

Remove extra dash from url


I have a blog system where user enter title and from it i make url here is the function to create url

function create_slug($string){     
    $replace = '-';         
    $string = strtolower($string);     

    //replace / and . with white space     
    $string = preg_replace("/[\/\.]/", " ", $string);     
    $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);     

    //remove multiple dashes or whitespaces     
    $string = preg_replace("/[\s-]+/", " ", $string);     

    //convert whitespaces and underscore to $replace     
    $string = preg_replace("/[\s_]/", $replace, $string);     

    //limit the slug size     
    $string = substr($string, 0, 100);     

    //slug is generated     
    return $string; 
}    

If user enter title "hello how are you" then it becomes "hello-how-are-you"!

Now the Problem I'm facing is that if user give extra space after "you " then it becomes "hello-how-are-you-". how to avoid this extra dash?


Solution

  • Just like Rizier123 says trim() will delete spaces before and after the entered value, don't forget that you have to trim() before you replace all the spaces with dashes.

    Because:

    trim() will make from "hello how are you " => "hello how are you"

    but from "hello-how-are-you-" it will make "hello-how-are-you-"