phpstringslugsanitizationkebab-case

Convert string to slug with no consecutive hyphens


I am trying to create a variable that performs a couple of different replacement rules. For example, if the variable name comes back with a space I replace it with a hyphen. If it contains an ampersand then it removes it from the string. Right now I have this:

$reg_ex_space = "[[:space:]]";
$replace_space_with = "-";
$reg_ex_amper = "[&]";
$replace_amper_with = "";
$manLink1 = ereg_replace ($reg_ex_amper, $replace_amper_with, $manName);
$manLink2 = ereg_replace ($reg_ex_space, $replace_space_with, $manLink1);

and when I echo manLink2 from something that has an ampersand, say Tom & Jerry, it will return Tom--Jerry.

Can someone please explain a more efficient/working way to write this?


Solution

  • This will replace & with blank string (removing it) and convert spaces to -.

    It will then condense multiple - together to one.

    $str = str_replace(array('&', ' '), array('', '-'), $str);
    
    $str = preg_replace('/-{2,}/', '-', $str);
    

    CodePad.