s1h4d0w
s1h4d0w

Reputation: 771

string replace <br /> to \n gives double breaks

Solution information:

The nl2br function does not replace \n with <br /> as I had expected but inserts a <br /> before the \n.

From php.net:

nl2br — Inserts HTML line breaks before all newlines in a string


Original question:

I'm replacing <br /> elements with \n in PHP, this is my input:

Top spot!<br />
<br />
123456789 123456789 123456789

This is my code:

$commenttext = str_replace("<br />", "\n", $reviewdata['comment']);

But my output is:

Top spot!



123456789 123456789 123456789

Is there something I'm missing with using str_replace? I'm getting double the breaks returned after using it.

Upvotes: 1

Views: 2021

Answers (2)

Gaurang Joshi
Gaurang Joshi

Reputation: 695

<?php

$text = 'top spot!<br />
<br />
123456789 123456789 123456789';

echo str_replace("<br />\n","\n",$text);

?>

DEMO

OUTPUT

top spot! 123456789 123456789 123456789

Upvotes: 1

Daniil Ryzhkov
Daniil Ryzhkov

Reputation: 7596

Let me show you. Your code before replacement:

Top spot!<br />\n<br />\n123456789 123456789 123456789

Your code after replacement:

Top spot!\n\n\n\n123456789 123456789 123456789

As you can see <br /> was correctly replaced with new line.

Try to replace <br /> tags with the new lines first:

$commenttext = str_replace("<br />\n", "\n", $reviewdata['comment']);

Upvotes: 3

Related Questions