Reputation: 12836
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?
Upvotes: 2
Views: 60
Reputation: 47894
To slugify your string, simply match one or more of any non-whitelisted characters then replace that matched substring with a single hyphen.
Code: (Demo)
$string = 'this is Tom & Jerry';
echo preg_replace('/[^a-z\d]+/i', '-', $string);
// this-is-Tom-Jerry
Upvotes: 0