tags:

views:

46

answers:

3

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

+3  A: 

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.

ryeguy
Double-quotes - tricky. I thought I was going mad.
Julian H. Lam
A: 

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.

Pascal MARTIN
Negated the downvote. This answer makes an excellent point. If you can be sure that everything you want to br2nl was created by nl2br, you're good to go. If you're interpreting user input, however, accepting any type of line break tag is a must.
Matchu
+2  A: 

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.

Coronatus
No, it's not evil. It's only a problem if you're using an XML doctype. And even then, it's easy to get around. Plenty of people use it in their views. It's much more compact than `<?php echo`.
ryeguy
<?= is evil? I thought only <? was evil ;)Guess I need to catch up on my coding practices... why is it evil, may I ask?
Julian H. Lam
@Julian They aren't evil, just use them where they're appropriate. This is most likely your view templates. The problem with the shortag syntax is that the XML doctype, `<?xml version="1.0"?>`, will be interpreted by PHP as a block of code, resulting in a syntax error. Now if you're not using XHTML, this isn't an issue, but if you are, you either have to give up using shorttags or just `echo` out the doctype (which is simple).
ryeguy