Matthew J. Kellett

Website Architect and Developer

Convert BR tags to Newline Characters

Intro

During my development process I am forever using the same information for both text-based emails and html-based emails. Then a thought came accross me, why not just use the same information and replace the <br /> with \n using some form of regular expressions. This lead to me doing a quick search on the net to ensure I wasn't reinventing the wheel and I came accross the following:

Usage

This function will convert line breaks or other tags passed in the $tags variable to linebreaks. Multiple $tags must be separated by spaces, and must consist of the regular tag text.

$result = br2nl($text_to_filter, "br p blockquote");

The Function

The function is as follows:

function br2nl($text, $tags = 'br') {
    $tags = explode(" ", $tags);
    foreach($tags as $tag) {
        $text = preg_replace('<' . $tag . '[^>]*>', '\n', $text);
        $text = preg_replace(']*>', '\n', $text);
    }
    return($text);
}

Enjoy and please feel free to leave a comment if you use this code

Comments

There are no comments for this article

Like, follow, share us

Code Categories

Use the links below to view each of the different code snippet categories

Latest Code Snippets

Below are the latest code snippets that I have written

Donations

If you like this code snippet or use it then please donate something to me so I can continue updating this as well as creating new ones