PHP Quick Script: Convert newline characters to xhtml break tags
PHP has it’s own function to convert newline characters to xhtml break tags, however more often than not it didn’t work for me at all so I decided to use the strtr() function instead of the default PHP function.
What the strtr() function does is return a copy of the string you gave it with certain single byte values that you chose completely replaced throughout the string. Normally the function would work like this…
[sourcecode language="PHP"]</p>
<p>strtr($string_to_convert, $from_value, $to_value);</p>
<p>[/sourcecode]
But you can also use an associative array to replace values much quicker like this…
[sourcecode language="PHP"]</p>
<p>strtr($string_to_convert, array("from value" => "to value"));</p>
<p>[/sourcecode]
We’re going to use the one with the associative array. Let’s see the script and then explain it further…
[sourcecode language="PHP"]</p>
<p>$string_to_convert = "This is a string\r\nwith a few newlines\rinside for demonstration\n\nUse it well.";</p>
<p>$var = strtr($string_to_convert, array("\r\n" => ‘<br />’, "\r" => ‘<br />’, "\n" => ‘<br />’));<br />
echo $var;</p>
<p>[/sourcecode]
First, we assign the function to a variable so that we can use it later on in our script. Now we insert the string to convert and seperated by a comma we insert the array. The array has 3 key value pairs, the first is \r\n which has to be first to ensure we convert it twice, ending up the two break tags instead of only one. Next is the individual \r and \n to also convert to break tags.
That’s it, this handy little function will allow you to convert newline characters to break tags without using the sometimes faulty nl2br() function or a resource intensive preg_replace() function.

You get a lot of respect from me for wiritng these helpful articles.