author: Krasimir Tsonev

Hi there, I'm . Senior front-end engineer with over 13 years of experience. I write, speak and occasionally code stuff.

Cleaning up <pre> tag content

I'm blogging for different technologies, but very often I need to add some code in my articles. This little PHP function helps me to keep the text in my <pre> tags clean for prettify. It simply removes the <br>'s and keeps the html tags.
function fixPreTags($str) {
    $parts = explode('<pre>', $str);
    $newStr = '';
    if(count($parts) > 1) {
        foreach ($parts as $p) {
            $parts2 = explode('</pre>', $p);
            if(count($parts2) > 1) {
                $code = str_replace('<br />', '', $parts2[0]);
                $code = str_replace('<br/>', '', $code);
                $code = str_replace('<br>', '', $code);
                $code = str_replace('<', '&lt;', $code);
                $newStr .= '<pre class="prettyprint linenums">'.$code.'</pre>';
                $newStr .= $parts2[1];
            } else {
                $newStr .= $p;
            }
        }
    } else {
        $newStr = $str;
    }
    return $newStr;
}
If you enjoy this post, share it on Twitter, Facebook or LinkedIn. Or maybe comment below: