The Little Guy Posted December 2, 2011 Share Posted December 2, 2011 I have the following function to format some code, I am having a problem though. between the code and example bbc tags new lines are converted to br's. I can't remember how to stop that from happening between those two tags, but do it everywhere else, can someone refresh my memory? My Attempt: public function format($string){ $string = preg_replace("/\<\?php.+\?\>/isUe", "highlight_string(str_replace('\\\"', '\"', '$0'), true);", $string); $string = preg_replace("/\[code\](.+)\[\/code\]/isU", "<span class='exampletxt'>EXAMPLE:</span><div class='code'>$1</div>", $string); $string = preg_replace("/\[example=(.+)\](.+)\[\/example\]/isUe", "html_entity_decode('$2');", $string); $string = preg_replace('/(<br\s*\/*>)/is', '', $string); $string = nl2br($string); return trim($string); } Thanks! Quote Link to comment Share on other sites More sharing options...
ragax Posted December 20, 2011 Share Posted December 20, 2011 Hi TLG, Here's one idea. The problem would be easy to solve if PCRE allowed negative lookbehinds of variable lengths. Then we could look behind the new line to see if there was a code div behind us. But PCRE doesn't allow that. You may have run into that. So, how about replacing all new lines unless they are inside a div? This may or may not suit your needs. It would certainly fix your problem for the bbc "code" tag. It would not suit your needs if you ever want to convert a new line that's inside a div... But would you want to do that? If the idea is appealing, here's an expression that replaces new lines with br tags unless the new lines are inside a div. The Match expression: (?!\r\n[^<]*?</div)\r\n The Replace expression: <br /> A sample preg: $string="First Line Second Line <div class='code'>blah blah</div"; $result = preg_replace('%(?!\r\n[^<]*?</div)\r\n%m', '<br />', $subject); echo htmlentities($result); The Input: First Line Second Line <div class='code'>blah blah</div The Output: First Line<br />Second Line<br /><div class='code'>blah blah</div So the new lines have been replaced with br tags, except inside the div. Is this a step in the right direction? Wishing you a fun day Quote Link to comment Share on other sites More sharing options...
ragax Posted December 22, 2011 Share Posted December 22, 2011 Hi again TLG, Another idea, a bit heavy but quite simple. Look for all the new lines between your tags, replace them with something unique such as ##NewLine##, do your br replacements on the rest of the strings, then switch back your ##NewLine## to new lines (\r\n). Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.