1

I have some code that is augmenting a regular expression by combining horizontal white-space and surrounding it in parentheses, unless it is already surrounded by non-backslashed parentheses. I have a piece of code that's working:

$regex_find = preg_replace('/(?<!\()[ \t]{2,}(?!\))/', '([ \t]{2,})', $regex_find);

However, for starters, the look-behind segnment, (?<!\(), should really allow for a literal left parenthesis, \(, but not a stand-alone left parenthesis, (.

Thanks

2
  • Adjusting from Bart's comment, we have: $s = '(\( ) b c d'; $s = preg_replace('/([^\t (])([ \t]{2,})([^\t )])/', '$1([ \t]{2,})$3', $s); Firstly, the replace does not allow for \( preceding the core string. And, yes, this left parenthesis would have to be single backslashed only. In addition, the right parenthesis needs to be tied into the left one. A proper solution of the above test string would be: (\(([ \t]{2,})) b c([ \t]{2,})d. Commented Jul 13, 2011 at 22:19
  • Actually, any odd number of backslashes preceding the inner left parenthesis would create a literal parenthesis. Commented Jul 13, 2011 at 23:16

1 Answer 1

1

Your original regex also has another problem. Try running it on this:

 $str = "asdf(     )sdf     sdf";
 //results in: "asdf( (   ) )sdf(     )sdf"

This regex should work:

$regex_find = '(    asdf(     )sdf     sdf';
preg_replace('/(?<!(\(|\s)(?=\s*\)))\s{2,}/','($0)',$regex_find);
//result = "((    )asdf(     )sdf(     )sdf"

Edit: Here is Qtax's solution with the additional lookbehind to ignore escaped \(

/(?<!((?<!\\)\(|\s)(?=\s*\)))\s{2,}/
Sign up to request clarification or add additional context in comments.

2 Comments

Great! But it's not checking escapes properly, could use another lookbehind, like /(?<!((?<!\\)\(|\s)(?=\s*\)))\s{2,}/: ideone.com/4cClT vs ideone.com/LmvVP
Get "Warning: preg_replace() [function.preg-replace]: Compilation failed: missing ) at offset 33..." in php 4.4.9. Perhaps it's more trouble than it's worth. Nested parentheses aren't the worst thing

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.