I need to replace:
我需要更换:
- All consecutive special characters by its single occurrence.
- I need to exclude
.
.
单次出现的所有连续特殊字符。
我需要排除..
e.g.
$about = " .....I......#### ";
should become
$about = " .....I......# ";
I wrote a regular expression:
我写了一个正则表达式:
$about = preg_replace("/[^\w^.]{2,}/","$1",$about);
but it is not working. How can I achieve this?
但它不起作用。我怎样才能做到这一点?
1 个解决方案
#1
2
Your pattern [^\w^.]{2,}
matches any 2 or more occurrences of a char other than word, ^
and .
.
您的模式[^ \ w ^。] {2,}匹配除了word,^和..之外的任何2个或多个char的匹配项。
To match consecutive identical chars other than word and a dot, you may use
要匹配除字和点之外的连续相同字符,您可以使用
([^\w.])\1+
and replace with $1
.
并以$ 1替换。
See the regex demo.
请参阅正则表达式演示。
Details:
-
([^\w.])
- matches and captures into Group 1 a char other than word char and a dot -
\1+
- matches 1 or more occurrences of the value captured into Group 1.
([^ \ w。]) - 匹配并捕获除了字char和点之外的字符组1
\ 1+ - 匹配1次或多次捕获到组1中的值。
The replacement pattern only inserts a single occurrence of the matched char.
替换模式仅插入匹配的char的单个匹配项。
$re = '/([^\w.])\1+/';
$str = ' .....I......#### ';
$subst = '$1';
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is '".$result . "'";
#1
2
Your pattern [^\w^.]{2,}
matches any 2 or more occurrences of a char other than word, ^
and .
.
您的模式[^ \ w ^。] {2,}匹配除了word,^和..之外的任何2个或多个char的匹配项。
To match consecutive identical chars other than word and a dot, you may use
要匹配除字和点之外的连续相同字符,您可以使用
([^\w.])\1+
and replace with $1
.
并以$ 1替换。
See the regex demo.
请参阅正则表达式演示。
Details:
-
([^\w.])
- matches and captures into Group 1 a char other than word char and a dot -
\1+
- matches 1 or more occurrences of the value captured into Group 1.
([^ \ w。]) - 匹配并捕获除了字char和点之外的字符组1
\ 1+ - 匹配1次或多次捕获到组1中的值。
The replacement pattern only inserts a single occurrence of the matched char.
替换模式仅插入匹配的char的单个匹配项。
$re = '/([^\w.])\1+/';
$str = ' .....I......#### ';
$subst = '$1';
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is '".$result . "'";