July 25th, 2010, 11:33 AM
[PHP] Using regex to add bracketing code
I'm having some difficulty with using preg_replace in PHP to find lines in a large block of HTML which do not contain a certain string and bracketing them with <em> tags.
Basically, I've got a huge block of text sent from a form, which I did nl2br on to make it display with spaces.
I now want to find anything that starts with two line breaks (<br /><br />) that then are *not* followed by a span tag, go all the way to the *next* set of line breaks, and surround the whole thing with <em></em>
In other words:
<br /><br />
<span class="gold">Some varying text here.</span><br /><br />
Some other text here, not wrapped in a span tag.<br /><br />
I'd like to do a preg_replace which finds the second line (because it does not have the <span> tag) and makes it italic.
Anyone have any thoughts on how to do this in PHP? Let me know if the question isn't clear or if you need more information. Thanks!
July 26th, 2010, 03:17 AM
1. The initial <br>s will have a line break after them. Use \s+ for that.
2. A negative assertion can check if the bit after isn't a <span> tag; it looks like (?!..).
3. An ungreedy dot-all for the rest, going up to a <br><br> or the end of the string.