Opposite of nl2br? Is it str_replace?

There will probably be some situations where your code is not enough ; so, what about something like this, to do your replacement :

$html = 'this <br>is<br/>some<br />text <br    />!';
$nl = preg_replace('#<br\s*/?>#i', "\n", $html);
echo $nl;

i.e. a bit more complex than a simple str_replace ;-)

Note : I would generally say don't use regex to manipulate HTML -- but, in this case, considering the regex would be pretty simple, I suppose it would be OK.


Also, note that I used "\n"

  • i.e. a newline : \n
  • in a double-quoted string, so it's interpreted as a newline, and not a literal \n


Basically, a <br> tag generally looks like :

  • <br>
  • or <br/>, with any number of spaces before the /

And that second point is where str_replace is not enough.


You'd want this:

<?=str_replace('<br />',"\n",$foo)?>

You probably forgot to use double quotes. Strings are only parsed for special characters if you use double quotes.

Tags:

Php