0

「ANYGROUP」または「ANYGROUP」として繰り返される「AnyGroup」をどのように一致させることができますか

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

そのため、「Foo Bar(Any Group-Baz)」として返されます。

セパレータは常に-

この投稿はRegex/PHPを拡張します繰り返し単語グループを置き換えます

これは「AnyGroup-ANYGROUP」と一致しますが、空白なしで繰り返された場合は一致しません。

$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);
4

2 に答える 2

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);
于 2012-11-03T15:25:18.183 に答える
0

最大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);

このデモを確認してください。

于 2012-11-03T16:00:24.767 に答える