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

6
  • 1
    Define "repeating word group" - does it have to be more than one word? How do you define a word? What separates words? How far may they be apart? Commented May 22, 2012 at 20:42
  • I think 2 notions are important for that: - The minimal length of the repeated group. - The possible separators between the groups. Commented May 22, 2012 at 20:43
  • The group could consist of 1-4 words while each word could match [A-Za-z0-9 \/\(\)]{1,30} Commented May 22, 2012 at 20:46
  • So if a space can be part of a word, how then are words separated from each other? Commented May 22, 2012 at 20:46
  • You are not really looking to replace a word, but an entire phrase which may be more difficult. Commented May 22, 2012 at 20:50

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.