Expression to remove two identical characters and other end characters
I have a php reg expression that removes any special character from any string and replaces the character with a hyphen. The problem is, if there are two special characters following each other, I get two hyphens. for example, if I type 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 identical 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);
Second, you are right-trimming (or regular) with a hyphen as an extra argument.
$slug = trim($slug, '-');
You can find some useful information here http://www.regular-expressions.info/repeat.html , basically you need to specify the repetition modifier.