Wednesday, June 24, 2009
PHP regular expression failing silently due to output buffering
I just had a problem where this regexp worked for finding the option with value 'foreign-relations' but not for finding 'economy':
'#(name="Section".*<option value="(.*)" selected="selected">.*</select></p>)#s'
The result was the dreaded PHP blank page. With no errors logged.
This fixed it:
'#(name="Section".*<option value="([\w\s-]*)" selected="selected">.*</select></p>)#s'
The second version is more specific about what string will match in the value attribute and I think that when specified with .* the match filled up the entire PHP memory buffer. If so, it wasn’t logged as an error and that could be because the code here is executed in ‘output buffering’ mode, following an ob_start() call. A guess, but if I am right that might help to avoid a lot of aggravation in future. [nb PHP: not providing error output is Bad.]
Corrections to this assumption welcome!
