Amit Dhamu

Software Engineer

Ignore nl2br() Inside Pre/Code Tag

To ensure new lines are saved as <br/>'s, I use PHPs built-in nl2br() function.

Inside an article however which may have a mixture of content such as <pre> or <code> tags, you don't want new lines created inside the content of those tags.

Therefore, I suggest using the function below.

# Change <code> for <pre> if required
function codenl2br($string) {
    $string = str_replace("n", "<br />", $string);
    if(preg_match_all('/<code>(.*?)</code>/', $string, $match)) {
        foreach($match as $a){
            foreach($a as $b){
              $string = str_replace('<code>'.$b.'</code>', "<code>".str_replace("<br />", "", $b)."</code>", $string);
    return $string;


nl2br / code / pre / line break / php

← List System Drives - Windows Only Detect AJAX Request in PHP →