Saturday, March 14, 2009

nl2br() function in PHP

While working with the RW/LL WAP community script, I noticed a bug(???), better say unexpected behaviour in nl2br() PHP library function. I had a function for processing bbcodes. I added the nl2br() in it to convert all the enter/return presses into the xhtml <br /> tags. But I noticed, in the forum posts all other bbcodes didn't work whenever a call to nl2br() occured due to enter presses. After fiddling with a lot of sequences(which I later found to be illogical on my part) of the processing lines of codes for bbcodes and the nl2br() function, I figured out that the problem is not with my code but PHP's implementation of the nl2br() function. So, with the help of the nl2br() manual comments on php.net I wrote my own nl2br() function as follows:
function nl2br1($text){
$text=str_replace(array("\r\n", "\r", "\n"), "[br/]", $text);
return $text;
}


Well, the above function takes into concern that:
On Windows the enter key press means "\r\n",
On Linux/UNIX/BSD and other UNIX derivatives the enter key press means "\n"
and on a Mac, it is "\r\".
Probably the built in nl2br() in PHP is implemented differently, so the glitch appeared.

No comments: