Jump to content

nl2br issue


The Little Guy

Recommended Posts

I have this code:

<?php
$content = preg_replace("/\<\?php.+\?\>/isUe", "highlight_string('$0', true);", $row['content']);
$content = nl2br($content);
echo $content;
?>

 

What it does is highlight the php, then it converts new lines to <br /> tags, but the problem is that it adds new lines in between the code tags. How can I get it to add new lines everywhere except between the code tags that are created by highlight_string?

Link to comment
https://forums.phpfreaks.com/topic/236182-nl2br-issue/
Share on other sites

Easiest way I can come up with is create an array of data to store the <code>, then strip out the data from <code> to </code>, placing a placeholder there, and running what you have left through the nl2br, then do a str_replace("{HOLDER_NUMBER",$content[$NUMBER],$content)

just an idea, and the only one I have.

 

working on a running code version right now.

Link to comment
https://forums.phpfreaks.com/topic/236182-nl2br-issue/#findComment-1214305
Share on other sites

Not sure if this will do, but here you go

/*Ok, this doesn't work if you have multiple <code> tags...*/
function hide_code_from_nl2br($input){
$content = $input;  //so I can remember what the heck I am doing
$code_begins = strstr($content,"<code>"); // Find where the code bracket starts.
$code_only_a = explode("</code>", $code_begins); //builds an array to get the end of the <code>, so we can keep it to itself
$code_only = $code_only_a[0]; // gets just the code
$content_minus_code = str_replace($code_only."</code>", "{CODE_GOES_HERE}", $content); //strips out the code from the content
return str_replace("{CODE_GOES_HERE}", $code_only."</code>", nl2br($content_minus_code)); //does an nl2br on what is left, and then adds the code back where it should be

}

I know there must be an easier way, but it was fun to write this way.

Link to comment
https://forums.phpfreaks.com/topic/236182-nl2br-issue/#findComment-1214309
Share on other sites

If I understand you correctly, and assuming that you're not putting in any line breaks manually before calling nl2br(), you can simply replace all line breaks prior to calling nl2br() since highlight_string() adds in the line breaks.

 

$content = preg_replace("/\<\?php.+\?\>/isUe", "highlight_string('$0', true);", $content);
$content = preg_replace('/(<br\s*\/*>)/is', '', $content);

$content = nl2br($content);

 

See if that does the trick.

Link to comment
https://forums.phpfreaks.com/topic/236182-nl2br-issue/#findComment-1214372
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.