PHP Function to Convert LineBreaks to NewLines

 –  Comments Off on PHP Function to Convert LineBreaks to NewLines

While PHP has a very nice little function (nl2br) to convert newlines (\n) to line breaks (<br>), moving in the opposite direction is not quite so easy. This function should hopefully help to allow you to convert line breaks to new lines.

<?php

/* 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.  Ie. $result = br2nl($text_to_filter, "br p blockquote") */
function br2nl($text, $tags = "br")
{
 $tags = explode(" ", $tags);

 foreach($tags as $tag)
 {
 $text = eregi_replace("<" . $tag . "[^>]*>", "\n", $text);
 $text = eregi_replace("</" . $tag . "[^>]*>", "\n", $text);
 }

 return($text);
}

// Usage:
 $text_to_filter = "<p>This is my <br>sample<br>text.  The default code listed here " .
"should replace the br's with new lines.</p><p>The second example is more advanced, " .
"stripping out both the BR's as well as the P tags.</p>";

 // Example of replacing BR tags (default)
 $result = br2nl($text_to_filter);
 echo "<pre>$result</pre>";

 // Example of replacing both BR and P tags
 $result = br2nl($text_to_filter, "br p");
 echo "<pre>$result</pre>";

?>

Related Reading:

The Joy of PHP: A Beginner's Guide to Programming Interactive Web Applications with PHP and mySQLThe Joy of PHP: A Beginner's Guide to Programming Interactive Web Applications with PHP and mySQLThird Edition now with bonus chapters. Have you ever wanted to design your own website or browser application but thought it would be too difficult or... Read More >
PHP and MySQL Web Development (5th Edition) (Developer's Library)PHP and MySQL Web Development (5th Edition) (Developer's Library)

PHP and MySQL Web Development, Fifth Edition

The definitive guide to building database-driven We... Read More >

PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (4th Edition)PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (4th Edition)It hasn't taken Web developers long to discover that when it comes to creating dynamic, database-driven Web sites, MySQL and PHP provide a winning ope... Read More >
Filed in: Code Snippets

Comments are closed.