Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 -

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
139 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
    '12', $subject);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...