我是正则表达式的新手。
我想替换字符串中的重复字符。这里有一些例子
$str1 = "aaa bbb cc dddd"; // output : a b c d
$str2 = "Google is the best"; // output : Google is the best
我在 stackoverflow 上发现了很多与此问题相关的问题。但它不满足我的要求。
我试过这个 (\w)\1
但这不是我的解决方案
有什么想法吗?提前致谢
编辑:
更多例子
$str1 = "this is tesaaat. are you ook?"; // output : this is tesaaat. are you ook?
$str2 = "Good morning mmmm yyyy friendssss "; // output : Good morning m y friends
$str3 = "Hello friendd okk"; // output : Hello friend okk
简而言之,我只想替换后面跟着空格的重复字符。
最佳答案
您可以使用以下正则表达式:\b(\w)\1+\b
。
解释:
- 分词符 (
\b
) - 单个字符
- 重复(至少一次相同的字符)
- 再一次,断词
编辑:如果有更多细节,我会说你可以去掉第一个 \b
。所以,它变成了:(\w)\1+\b
关于php - 替换重复字符正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19611499/