【问题标题】:Regex/PHP Replace any repeating (but flexible) word group正则表达式/PHP 替换任何重复(但灵活)的词组
【发布时间】:2012-10-24 00:14:48
【问题描述】:

如何匹配重复为“ANY GROUP”或“ANYGROUP”的“Any Group”

$string = "Foo Bar (Any Group - ANY GROUP Baz)
           Foo Bar (Any Group - ANYGROUP Baz)";

所以他们以“Foo Bar (Any Group - Baz)”的形式返回

分隔符总是-

这篇文章扩展了Regex/PHP Replace any repeating word group

这匹配“Any Group - ANY GROUP”,但在没有空格的情况下不匹配。

$result = preg_replace(
    '%
    (                 # Match and capture
     (?:              # the following:...
      [\w/()]{1,30}   # 1-30 "word" characters
      [^\w/()]+       # 1 or more non-word characters
     ){1,4}           # 1 to 4 times
    )                 # End of capturing group 1
    ([ -]*)           # Match any number of intervening characters (space/dash)
    \1                # Match the same as the first group
    %ix',             # Case-insensitive, verbose regex
    '\1\2', $subject);

【问题讨论】:

    标签: php regex


    【解决方案1】:

    这很丑陋(正如我所说的那样),但它应该可以工作:

    $result = preg_replace(
        '/((\b\w+)\s+)               # One repeated word
        \s*-\s*
        \2
        |
        ((\b\w+)\s+(\w+)\s+)         # Two repeated words
        \s*-\s*
        \4\s*\5
        |
        ((\b\w+)\s+(\w+)\s+(\w+)\s+) # Three
        \s*-\s*
        \7\s*\8\s*\9
        |
        ((\b\w+)\s+(\w+)\s+(\w+)\s+(\w+)\s+)  # Four
        \s*-\s*
        \11\s*\12\s*\13\s*\14\b/ix', 
        '\1\3\6\10-', $subject);
    

    【讨论】:

    • 谢谢。是的,“任何组”中的 1-4 个单词完全可以。抱歉,不清楚。
    • 将所有\s* 修复为\s+ tho,否则Foo Bar (Any Group - ANY GROUPXYZ Baz) 会出现问题。
    • “问题”是什么意思?在这种情况下应该是什么结果?可能有比使用 \s+ 更好的解决方案(我将空格设为可选是有原因的)。
    • Foo Bar (Any Group - ANY GROUPXYZ Baz) 变为 Foo Bar (Any Group - XYZ Baz) 但应该保持不变,因为它不一样。 \s+ 可以防止这种情况发生,因为 ANY GROUP 之后必须有一个空白。 \s* 使其可选。
    • 好的(你可以指定你只想匹配整个单词),这很容易通过单词边界锚来实现:\b 只匹配单词的开头和结尾。
    【解决方案2】:

    最多 6 个单词的解决方案是:

    $result = preg_replace(
        '/
         (\(\s*)
         (([^\s-]+)
          \s*?([^\s-]*)
          \s*?([^\s-]*)
          \s*?([^\s-]*)
          \s*?([^\s-]*)
          \s*?([^\s-]*))
         (\s*\-\s*)
         \3\s*\4\s*\5\s*\6\s*\7\s*\8\s*
         /ix',
         '\1\2\9',
         $string);
    

    检查this demo

    【讨论】:

    • 谢谢。不幸的是,这删除了“任何组”中的空白。已将 ideone.com 加入书签 ;)
    • 现在有了...\8\s+ 就完美了!谢谢你们。
    猜你喜欢
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    相关资源
    最近更新 更多