Hey all.. I am trying to replace "\n" to '<br />' BUT, not inside PHP: <?php ?> or tags.. Any suggestions? Josh Ive tried figuring out negative lookbehind assertion things but I am not too sure.. #\n(!<?php+)#sie
/((?:\\n(?<!(?:.*?)?<\?(php)?(?:.*?)?))|(?:\\n(?<=(?:.*?)?\?>(?:.*?)?)))/si PHP: that will match any \n that is no inside of <? ?> or <?php ?> there might be a shorter method but meh, this works edit: could use a little work though. will only work if there is 1 set of php braces.
A lookbehind must be fixed width in most regex flavors, including PHP. Personally I'd be tempted to do this by first replacing all the "\n" within the <?php ?> blocks (since that's very easy to find) to something else. Then you can safely convert any remaining \n to <br />, and do a final replace to get the \n back from within the <?php ?> tags. Untested but something like: $string = preg_replace('#<\?(?:php)?(.*?)\?>#se', 'str_replace("\n", "__PRESERVEn__", stripslashes(\'\\1\'))', $string); $string = str_replace("\n",'<br />',$string); $string = str_replace('__PRESERVEn__',"\n",$string); PHP:
Thanks for the quick replies, but I am still having trouble... Heres what I am doing right now: function acms_nl2br($text) { $text = str_replace("\r", '', $text); $text = str_replace("\n", '<br />', $text); return $text; } PHP: function parse_bbcode($text, $nl2br='0') { $text = $this -> parse_bbcode_codetag($text); $text = $this -> parse_bbcode_phptag($text); $text = $this -> parse_smilies($text); if ($nl2br != 0) { $text = $this -> acms_nl2br($text); } ... plus some more here... PHP: Now, if I do NL2BR after I call the php bbcode parser I get a blank line before and after the <?php ?> which is done like so.. $replacement = $start_html . highlight_string("<?php\n" . $after_replace . "\n?>", 1) . $end_html; Now... If I replace all <br /> from inside the php function to \n - it shows up perfectly at the cost of ruining the nl2br formatting everywhere else (IF I CALL NL2BR BEFORE CALLING THE PHP TAG)... If I call nl2br before, then replace from within php (which is essentially like not calling it) EDIT: Ok, Im trying to call the nl2br first, then inside the php function I can replace all brs with newlines inside PHP: If I find a solution Ill post Thanks all EDIT: No sleep really screws you over... I was using preg_match_all to locate the php tags, basically you simply replace the match with $matches[1][$i] = str_replace('<br />', "\n", $matches[1][$i]);