In brief
Given a string like this –
MAX_checkTime_Hour('0,1', '=~') and (MAX_checkTime_Day('1,2', '=~') or MAX_checkTime_Day('1,2', '=~')) and MAX_checkGeo_Country('DZ,AO,BJ)
I want to insert <br /> tags before and in between patterns like and MAX_ or and (MAX_ or and ((MAX_ and so on, so that the output is –
MAX_checkTime_Hour('0,1', '=~')<br /> and <br />(MAX_checkTime_Day('1,2', '=~') or MAX_checkTime_Day('1,2', '=~'))<br /> and <br />MAX_checkGeo_Country('DZ,AO,BJ)
What I have done so far
With the following regex replacement I am almost there. The insertion of <br /> tags is working but I am having to insert a fixed number of s –
preg_replace("/\s+and\s+MAX_/",'<br /> and <br />MAX_',$str);
I wanted to –
- preserve the exact number of whitespaces.
- preserve the exact number of first brackets before
MAX_.
So, if the original string was like this –
MAX_checkTime_Hour('0,1', '=~') <3 white spaces here> and <5 white spaces here> #2 first brackets here#MAX_checkTime_Day('1,2', '=~')
I would like the output to be –
MAX_checkTime_Hour('0,1', '=~')<br /> <3 white spaces here> and <5 white spaces here> <br /><first brackets here>MAX_checkTime_Day('1,2', '=~')
Update
I tried with the following assuming that the variable number of whitespaces would be stored in variables, but it did not work –
preg_replace("/{\s+}and{\s+}MAX_/",'<br />$1and$2<br />MAX_',$str);
I suppose you forgot about ‘or’ operator in the source (located right before third MAX_). There is alt. version of regexp – it’s more generic (because it can match and safely replace both ‘and’ & ‘or’ operators) and it has been little more optimized (because it doesn’t use look-ahead/look-behind syntax):
Also it DRY compatible, replacement string doesn’t contains any parts of the source string