Page 1 of 1

nl2br() puts break inside tag

Posted: Sun Jan 31, 2010 11:29 pm
by gmichtom
I am a novice at PHP but an experienced programmer. I am extracting some data from a DB and displaying it on the webpage. I am using nl2br() to ensure the formatting looks appropriate. Unfortunately, there is at least one passage to display that has an HTML link in it, with a newline embedded in a link, thusly:

...lots of interesting text yadda yadda yadda <a href=
"http://the.links.url">click me</a>and yet more stuff....

nl2br() happily replaces the newline in the link with a <br> thus messing up not only the link itself but the subsequent text display. If I don't use nl2br(), then all the text in all passages are displayed as a single block of text.

Short of writing a function to parse the text and determine if the newline is within a tag, any other suggestions for how to make the formatting good but not mess up the tag? I was surprised there wasn't an option in nl2br() to skip tags, or some other function which does a similar thing. Did I miss it?

Updating the DB to remove the newline is possible but I'd have to search all for such instances, then prevent such future transgressions. Right now I don't have control over what goes in.

Re: nl2br() puts break inside tag

Posted: Mon Feb 01, 2010 2:38 am
by JakeJ
How the heck is a line break getting inside of your tag? That's really screwed up!

In any case, you could try the strip_tags() function. Run all your text through that as you pull it out of the database.

Check out this link: http://php.net/manual/en/function.strip-tags.php

Not only is it the manual for that function, but there are some modified functions you can use that might suit you as well.

I hope that helps.

Re: nl2br() puts break inside tag

Posted: Mon Feb 01, 2010 5:48 pm
by gmichtom
I considered that. Unfortunately, that will remove the link from the text. A user would have to copy/paste the link's text (which is presented in the text) to follow the link. It also eliminates any other useful tags that someone might put in their text.

What I want is a version of nl2br() which ignores text within HTML tags. But I fear such a thing does not exist.

Re: nl2br() puts break inside tag

Posted: Mon Feb 01, 2010 7:15 pm
by AbraCadaver
gmichtom wrote:I considered that. Unfortunately, that will remove the link from the text. A user would have to copy/paste the link's text (which is presented in the text) to follow the link. It also eliminates any other useful tags that someone might put in their text.

What I want is a version of nl2br() which ignores text within HTML tags. But I fear such a thing does not exist.
You are correct. You're going to have to use a preg_replace() that ignores \n inside a tag.