[英]regex replace occurrence of two character with one.
I am trying to implement a regular expression that will replace the occurrence of two or more characters with one. 我正在尝试实现一个正则表达式,该表达式将用一个字符代替两个或多个字符的出现。 but I didn't know to do this. 但我不知道这样做
this is my string 这是我的弦
example--of---string.
I need a regular expression that will give me output like this 我需要一个正则表达式,它将给我这样的输出
example-of-string.
Is this is possible in regular expression, preg_replace in php. 这是可能的正则表达式,在PHP中的preg_replace。
or I need to access the elements though array and check for next character and skip if it is - 或者我需要通过数组访问元素并检查下一个字符并跳过是否为-
Please advise me 请建议我
(.)\1+
This will pick up any occurrence of the same character repeated more than twice. 这将拾取重复出现两次以上的同一字符的任何出现。 Not just dashes. 不只是破折号。
\1
<?php
$string = 'example--of---string.';
$new_string = preg_replace('/-+/', '-', $string);
echo $new_string;
?>
Use this regex: 使用此正则表达式:
/-{1,}/g
Replace with: 用。。。来代替:
-
Demo: http://regex101.com/r/uV1qZ7 演示: http : //regex101.com/r/uV1qZ7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.