-1

How can match

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

Should return as "Foo Bar (Any Group - Baz)"

Is it possible without bruteforce as here Replace repeating strings in a string ?

Edit: * The group could consist of 1-4 words while each word could match [A-Za-z0-9\/\(\)]{1,30} * The separator would always be -

Community
  • 1
  • 1
Martin
  • 2,007
  • 6
  • 28
  • 44

1 Answers1

5

Leaving the space out of the list of allowed "word" characters, the following works for your example:

$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);
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Hi, I need to bump this old thread. Would it be possible to ignore possible blanks? So "(Any Group - ANYGROUP Baz)" would return "(Any Group - Baz)" ? – Martin Nov 02 '12 at 12:31
  • @Martin: I can think of an (ugly) way how this could work, but it would be a completely different approach than the one I've used here, so I think this should be put into a new question to avoid confusing people. – Tim Pietzcker Nov 02 '12 at 14:05