Search code examples
phpstringurlphp-7slug

String replace to replace spaces and maintain dash


I am trying to convert:

" Long Grain IRRI-6 White Rice "

to

" long_grain_irri_6_white_rice "

but it's returning this

" long_grain_irri-6_white_rice "

Here is the code:

public function phpslug($string){
    $slug = preg_replace('/[^a-z0-9-]+/', '_', strtolower($string));
    return $slug;
}

I want it to remove not only space between letters, I need it to remove also "-" this, so it can replace with "_".

How do I solve this problem?


Solution

  • You might remove - from your RegEx pattern:

    function phpslug($string)
    {
        $slug = preg_replace('/[^a-z0-9]+/', '_', strtolower(trim($string)));
        return $slug;
    }
    
    var_dump(phpslug("  Long Grain IRRI-6 White Rice  "));
    

    or you might simplify your RegEx pattern:

    function phpslug($string)
    {
        $slug = preg_replace('/[-\s]+/', '_', strtolower(trim($string)));
        return $slug;
    }
    
    var_dump(phpslug("  Long Grain IRRI-6 White Rice  "));
    

    Output:

     string(28) "long_grain_irri_6_white_rice"