View Full Version : Regular Expressions

03-09-2007, 09:58 AM
Hello. I've been having a bit of trouble with some code that I've been writing, which deals with regular expressions, and more specifically with translating BB Code to HTML code and vice versa. The first bot of code takes a normal bit of text (from whatever the user posted) and runs it through a preg_replace, changing BB Code to HTML. The second bit does the opposite: it takes some text and changes all the HTML to BB Code (so the user can see the BB Code when he edits the text). For some reason, the first bit isn't working as I expected, pretty much only with the url img and quote tags. The second bit works as far as I know. On a side note, how would I change breaks in what a user has typed (in a textarea) into <br>'s with regular exprecssions? I tried using /n, but that didn't seem to work, or at least I couldn't get it to. Anyway, please excuse any really stupid sounding grammar, it's about 4am and I've been having a bit of trouble concentrating. Thanks in advance! :thumbsup:

Bit of code 1:

$input = array( "/\/", "/\[\/b\]/",
"/\[i\]/", "/\[\/i\]/",
"/\[u\]/", "/\[\/u\]/",
"/\/", "/\[\/url\]/",
"/\[quote\](.*?)\[\/quote\]/" );

$code = array( "<b>", "</b>",
"<i>", "</i>",
"<u>", "</u>",
"<a href='\${1}'>", "</a>",
"<img src='\${1}'>",
"<div class='quote-box-right'>\${1}</div>" );

$message = preg_replace($input,$code,$message);

Bit of code 2:

$code = array( "[b]", "",
"", "",
"", "",
"[url=\${1}]", " ((.*?)\)",
\${1}" );

$input = array( "/\<b\>/", "/\<\/b\>/",
"/\<i\>/", "/\<\/i\>/",
"/\<u\>/", "/\<\/u\>/",
"/\<a href=\"(.*?)\"\>/", "/\<\/a\>/",
"/\<img src=\"(.*?)\"\>/",
"/\<div class=\"quote-box-right\"\>(.*?)\<\/div\>/" );

$message = preg_replace($input,$code,$message);