regex not matching spaces on text between parentheses

Viewed 100

Why doesn't this regex match white space on text between parentheses? \((?:(\(\s>)|(\s{2,})|(\s\)))\)

The text below it that isn't enclosed in parenthesis should be ignored. It's just there. No need to worry with that. Only the ones in parentheses need to be touched.

(  R:2379; L:  28 ) //replace to (R:2379;L:28)
R:2379;L:28
(R:2432;L:28) // ok, no replacements needed
R:2432; L:28
( R  :  2475; L:    28   ) // replace to (R:2475;L:28)
R:2475; L:28
(     R : 2480   ; L:28 ) // replace to (R:2480;L:28)
R:2480; L:28

Edit:

(  R:2379; L:  28 ) //replace to (R:2379; L:28) #a single space is ok, except before or after a parentheses. Multiple spaces are reduced to blank.
(R:2432;L:28) // ok, no replacements needed
(R:2432; L: 28) // ok, no replacements needed. The single spaces are not before or after the parentheses
( R  :  2475; L:    28   ) // replace to (R:2475; L:28) #the single space before the L is fine. other multiple spaces are blanked
(     R : 2480   ; L: 28 ) // replace to (R:2480; L: 28) #the single space before the 28 is fine
1 Answers

You can use

preg_replace('/(?:\G(?!\A)|\()[^()]*?\K(?:(?<=\()\s+|\s+(?=\))|\s{2,})(?=[^()]*\))/', '', $string)

See the regex demo. Details:

  • (?:\G(?!\A)|\() - either the end of the previous match or (
  • [^()]*? - zero or more chars other than (, ), as few as possible
  • \K - omit the text matched so far
  • (?:(?<=\()\s+|\s+(?=\))|\s{2,}) - 1+ whitespaces right after (, or 1+ whitespaces right before (, and any two or more whitespace characters
  • (?=[^()]*\)) - that are followed with any 0 or more chars other than ( and ) and then a ).
Related