Shoe
Shoe

Reputation: 76300

Capture new line in a string

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>?

Upvotes: 0

Views: 102

Answers (5)

Alex
Alex

Reputation: 7688

Why don't you use:

$string = "
This is a line\n
This is another line
";

? or use

$string = <<<EOF
    This is a line
    This is another line
EOF;

Upvotes: 0

MetalFrog
MetalFrog

Reputation: 10543

If you're not getting it with nl2br, your new line character must not be \n.

print nl2br( str_replace( array( "\r\n", "\r" ), "\n", $string);

Upvotes: 0

Konrad Dzwinel
Konrad Dzwinel

Reputation: 37923

Use nl2br function like this:

echo nl2br($string);

Upvotes: 1

webbiedave
webbiedave

Reputation: 48887

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 />
*/

Upvotes: 2

Bailey Parker
Bailey Parker

Reputation: 15903

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

Upvotes: 2

Related Questions