I am writing a BB code decoder and encoder using regular expressions and the preg_replace() function in php.
i am mostly using this type of regex and its works really well
$text = preg_replace("/\[b\](.*)\[\/b\]/", "<strong>\\1</strong>", $text);
My problem is with lists, I write them like this in the BB code:
[numlist]
[*]number list
[*]number list
[*]number list
[/numlist]
But because i use nl2br() at then end of my encoder function that BB code up there generates alot of extra br tags, after these replace functions are called on that bit of code;
$text = preg_replace("/\[numlist\](.*)\[\/numlist\]/sm", "<ol class='pol'>\\1</ol>", $text);
$text = preg_replace("/\[\*\](.*)/", "<li>\\1</li>", $text);
I end up with this:
<ol class='pol'><br />
<li>number list<br />
</li><br />
<li>number list<br />
</li><br />
<li>number list<br />
</li><br />
</ol><br />
so in my css right now I have to add margin:0px 0px -30px 40px; to the ol li markup so it looks right, but its just ugly.
My question comes down to this; How can I use regular expressions to look for all linebeaks within my [numlist] [/numlist] code and remove them?
<br>
tags you should use a more clever nl2br approach. E.g. only replace each double newline\n\r?\n
with a<br><br>
. Otherwise you would need to prepare a real parser. (The post-fix approach btw would be a preg_replace_callback on the list tag, and a preg_replace within that to clean up thebr
tags. A single regex can't easily do that.) – mario Dec 11 '11 at 21:18I have bold text [b]here[/b] and [b]here[/b].
Is "and" bold? It's between[b]
and[/b]
, after all. So ... +1 for recycling existing code for this instead of reinventing the wheel. – ghoti Dec 12 '11 at 6:51