Php 如何将双字母/多字母替换为单个字母?

Php 如何将双字母/多字母替换为单个字母?,php,regex,Php,Regex,我需要将一个单词中出现两次或两次以上的字母转换为一个字母 例如: School -> Schol Google -> Gogle Gooooogle -> Gogle VooDoo -> Vodo 我尝试了以下方法,但仍停留在eregi_replace中的第二个参数上 $word = 'Goooogle'; $word2 = eregi_replace("([a-z]{2,})", "?", $word); 如果我使用\\\1替换?,它将显示精确匹配。 我怎样才能写一

我需要将一个单词中出现两次或两次以上的字母转换为一个字母

例如:

School -> Schol
Google -> Gogle
Gooooogle -> Gogle
VooDoo -> Vodo
我尝试了以下方法,但仍停留在eregi_replace中的第二个参数上

$word = 'Goooogle';
$word2 = eregi_replace("([a-z]{2,})", "?", $word);
如果我使用
\\\1
替换?,它将显示精确匹配。 我怎样才能写一个字母呢


有人能帮忙吗?谢谢

您不仅捕获了整个内容(而不仅仅是第一个字符),而且还重新匹配了[a-z](不是原始匹配)。如果您使用:

$word2 = eregi_replace("(\w)\1+", "\\1", $word);
它反向引用了原始匹配。如果愿意,可以将\w替换为[a-z]

您的Goooogle示例需要+(无论如何,对于JS正则表达式引擎),但我不确定为什么

请记住,您需要使用“全局”标志(“g”)。

请参阅

顺便说一下:您应该使用
preg.*
(PCRE)函数,而不是不推荐使用的
ereg.*
函数(POSIX)

的答案是正确的:

$word = 'Goooogle';
$word2 = preg_replace('/(\w)\1+/', '$1', $word);
试试这个:

$string = "thhhhiiiissssss hasss sooo mannnny letterss";
$string = preg_replace('/([a-zA-Z])\1+/', '$1', $string);
工作原理:

/ ... /    # Marks the start and end of the expression.
([a-zA-Z]) # Match any single a-z character lowercase or uppercase.
\1+        # One or more occurrence of the single character we matched previously.

$1         
\1+        # The same single character we matched previously.

哥们,太棒了。我想我得换成PCRE了!谢谢<代码>\w匹配的不仅仅是字母。它与
[a-zA-Z0-9\]
匹配。