简体   繁体   中英

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.

I found the answer is pretty simple. I simply use

$text = $this->storyContent;
$text = str_replace("\\r\\n","<br>",$text);
$text = str_replace("\\n\\r","<br>",$text);
$text = str_replace("\\r","<br>",$text);
$text = str_replace("\\n","<br>",$text);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM