代码之家  ›  专栏  ›  技术社区  ›  uuɐɯǝʃǝs

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

  •  4
  • uuɐɯǝʃǝs  · 技术社区  · 15 年前

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

    例如:

    School -> Schol
    Google -> Gogle
    Gooooogle -> Gogle
    VooDoo -> Vodo
    

    我尝试了下面的方法,但仍然停留在eregi_replace中的第二个参数上。

    $word = 'Goooogle';
    $word2 = eregi_replace("([a-z]{2,})", "?", $word);
    

    如果我使用 \\\1 替换?,它将显示完全匹配。 我怎么写一封信?

    有人能帮忙吗?谢谢

    3 回复  |  直到 8 年前
        1
  •  8
  •   Community paulsm4    7 年前

    regular expression to replace two (or more) consecutive characters by only one?

    顺便问一下:你应该用 preg_* (PCRE)函数,而不是弃用的 ereg_* 函数(posix)。

    Richard Szalay 答案是正确的:

    $word = 'Goooogle';
    $word2 = preg_replace('/(\w)\1+/', '$1', $word);
    
        2
  •  2
  •   Richard Szalay    15 年前

    你不仅捕获了整件事(而不仅仅是第一个角色),而且 {2,} 重新匹配[A-Z](不是原始匹配)。如果您使用:

    $word2 = eregi_replace("(\w)\1+", "\\1", $word);
    

    它引用了原始匹配。如果愿意,可以用[a-z]替换\w。

    对于您的Google示例(不管怎样,对于JS Regex引擎),需要使用+键,但我不知道为什么。

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

        3
  •  1
  •   Will Brian Hodge    9 年前

    试试这个:

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