php regex surround string with parentheses unless already surrounded by non-literal parentheses
I have some code that is augmenting a regular expression by combining horizontal white开发者_Python百科-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
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,}/
精彩评论