Convert line breaks and tabs between textarea (html), PHP and CKEditor5 (Javascript)

Post Photo
Friday, 18th September 2020

I am using CodeIgniter 3. In order to publish code using the pre tag I had to translate line breaks and tabs when editing my posts. This is what I came up with

First of all I am checking if a <pre> tag exists in my post. Most of my blog posts don't include any <pre> tag simply because they don't contain any source code box.

If no <pre> tag is found it just returns the string unmodified.

rn2br

This converts PHP \r\n and \t to <br> and 4 spaces (the official definition of tab).

I use this mode for saving my posts to the database (MySQL).

br2entity

This converts <br> and 4 spaces to HTML entities.

I use this mode when reading my database to a <textarea> tag.

rn2entity

The tricky part. It converts PHP \r\n and \t to HTML entities.

I use this to give my saved post data to CKEditor again. You know. When you save your post it re-appears in your form. You give it to CKEditor in order to continue editing.

Have fun using this function.

/**
* Fix Line Breaks
*/

function fix_br($str, $modus) {

if (mb_strpos($str, '<pre>') === false) {return $str;}
    
$result = $str;
    switch ($modus) {
        case 'rn2br':
            $result = str_replace("\r\n","<br>", $str);
            $result = str_replace("\t","&nbsp;&nbsp;&nbsp;&nbsp;", $result);
            break;
        case 'br2entity':
            $result = str_replace("<br>", "&#13;&#10;", $str);
            $result = str_replace("&nbsp;&nbsp;&nbsp;&nbsp;","&#9;", $result);
            break;
        case 'rn2entity':
            $result = str_replace("\r\n", "&#13;&#10;", $str);
            $result = str_replace("\t","&#9;", $result);
            break;
        default:
            break;
    }
return $result;

}

Share Post

If you like this post please share with your friends