Search code examples
phpnl2br

How to add new line in php echo


The text of story content in my database is:

I want to add\r\nnew line

(no quote)

When I use:

echo nl2br($story->getStoryContent());

to replace the \r\n with br, it doesn't work. The browser still display \r\n. When I view source, the \r\n is still there and br is nowhere to be found also. This is weird because when I test the function nl2br with simple code like:

echo nl2br("Welcome\r\nThis is my HTML document");

it does work. Would you please tell me why it didn't work? Thank you so much.


Solution

  • The following snippet uses a technique that you may like better, as follows:

    <?php
    
    $example = "\n\rSome Kind\r of \nText\n\n";
    
    
    $replace = array("\r\n", "\n\r", "\r", "\n");
    $subs    = array("","","","");
    
    $text = str_replace($replace, $subs, $example );
    var_dump($text); // "Some Kind of Text"
    

    Live demo here

    I doubt that you need "\n\r" but I left it in just in case you feel it is really necessary. This works by having an array of line termination strings to be replaced with an empty string in each case.