Search code examples
phpcarriage-return

PHP's nl2br is not working correctly


For example, I have:

Lorem Ipsum

Dolor Sir Amet

As the content of $s. Now if I print the result of htmlspecialchars(nl2br($s)) is:

Lorem Ipsum<br />
<br />
Dolor Sir Amet

While the result I want is:

Lorem Ipsum<br /><br /> Dolor Sir Amet

Why the nl2br is not removing the carriage return even though it's already inserting the <br /> ? Or how is the correct usage of nl2br to correctly remove the carriage return? Because this breaks my SQL. I'm running PHP on Apache in Windows 7. Thanks.


Solution

  • to replace all linebreaks to <br /> you should use an extended function,
    here it is an example:

    <?php 
    function nl2br2($string) { 
    $string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string); 
    return $string; 
    } 
    

    Each OS have different ASCII chars for linebreak:

    windows = \r\n
    unix = \n
    mac = \r