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...
The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (\n) in a string.
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.
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"
\n
\n
Basically, a <br>
tag generally looks like :
<br>
<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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With