表达式删除两个相似的字符和其他尾随字符
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);
我有一个php reg表达式,可以从任何字符串中删除任何特殊字符,并用连字符替换该字符。 问题是,如果彼此之后有两个特殊字符,我会得到两个连字符。 例如,如果我输入文本 test @hhh%^ code>我得到
test-hhh - code>或者如果我输入
test @hhh%^ kkk code> 我得到
test-hhh - kkk code>。 我希望我的表达能给我
test-hhh code>。 我想删除两个相似的连字符以及字符串中的任何尾随连字符。 我的代码在这里 p>
$ slug = preg_replace('/ [^ a-zA-Z0-9] /',' - ',$ slug);
代码> pre>
div>
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.