Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of nl2br? Is it str_replace?

Tags:

php

So the function nl2br is handy. Except in my web app, I want to do the opposite, interpret line breaks as new lines, since they will be echoed into a pre-filled form.

str_replace can take <br /> and replace it with whatever I want, but if I put in \n, it echoes literally a backslash and an n. It only works if I put a literal line break in the middle of my script, and break the indentation (so there are no trailing space).

See:

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

Am I missing escape characters? I think I tried every combination...

like image 919
Julian H. Lam Avatar asked Mar 22 '10 18:03

Julian H. Lam


People also ask

What does nl2br mean?

The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (\n) in a string.

What is Br in PHP?

Using Line Breaks as in HTML: The <br> tag in HTML is used to give the single line break. It is an empty tag, so it does not contain an end tag. Syntax: </br> Example: PHP.


3 Answers

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.

like image 104
Pascal MARTIN Avatar answered Nov 04 '22 02:11

Pascal MARTIN


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.

like image 35
ryeguy Avatar answered Nov 04 '22 03:11

ryeguy


Are you writing '\n'? Because \n will only be interpreted correctly if you surround it with double quotes: "\n".

Off topic: the <?= syntax is evil. Please don't use it for the sake of the other developers on your team.

like image 12
Amy B Avatar answered Nov 04 '22 04:11

Amy B