I know for sure that this was already been asked before but I just googled around and couldn't find anything (maybe wrong word choice?). Just don't be too mad at me, I'm getting mad too...
I'd like
$string = '
This is a line
This is another line
';
to be shown to the HTML page as
This is a line
This is another line
when I do echo $string;
. How can I capture the return key or the new line and replace it with <br>
?
Try the nl2br()
function:
echo nl2br($string);
Would return:
<br>
This is a line<br>
This is another line<br>
To trim off the leading and trailing new lines, use trim()
:
echo nl2br(trim($string));
Would return:
This is a line<br>
This is another line
You can use the PHP function nl2br. It doesn't replace the newlines but, rather, inserts <br />
next to them (which is perfectly fine for your purposes).
Using your example:
$string = '
This is a line
This is another line
';
echo nl2br($string);
/* output
<br />
This is a line<br />
This is another line<br />
*/
Use nl2br
function like this:
echo nl2br($string);
If you're not getting it with nl2br, your new line character must not be .
print nl2br( str_replace( array( "
", "" ), "
", $string);
Why don't you use:
$string = "
This is a line
This is another line
";
? or use
$string = <<<EOF
This is a line
This is another line
EOF;