I have a php reg expression that removes any special character from any string and replaces the character with a hyphen. The problem is that if there are two special characters following each other, I get two hyphens. for example if I type the text test@hhh%^
I get test-hhh--
or if I type test@hhh%^kkk
I get test-hhh--kkk
. I want my expression to give me test-hhh
. I want to remove two similar hyphens following each other plus any trailing hyphens in the string. My code is here
$slug = preg_replace('/[^a-zA-Z0-9]/', '-', $slug);
First apply this regex to your string:
$slug = preg_replace('#-{2,}#', '-', $slug);
Secondly you apply a right trim (or a regular one) with a hyphen character as an extra argument.
$slug = trim($slug, '-');
You can find useful info here http://www.regular-expressions.info/repeat.html, basically you need to specify a repetition modifier.