php - 替换重复字符正则表达式

标签 php regex

我是正则表达式的新手。

我想替换字符串中的重复字符。这里有一些例子

$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/

相关文章:

regex - Traceroute 输出的正确正则表达式

javascript - 仅针对空白区域进行正则表达式验证;应该接受单词/字符之间的空格

regex - 背后的Powershell反向引用

apache - Nginx自定义error_page没有使用指定页面?

php - CSS、PHP、mySQL Loop - 根据变量更改 td 颜色

php - 从 Google_Service_AnalyticsReporting (google/apiclient SDK) 切换到 BetaAnalyticsDataClient (google/analytics-data SDK)

php - 在投票系统上每人只允许投一票

java正则表达式提取带有边界和可选空格的数字

php - 如何使用 ffmpeg 和 PHP 创建图像?

java - 查找字符串中嵌入的 xpath