tags:

views:

699

answers:

2

how can I remove excess <br> and &nbsp; tags from the start and end of a string?

Thanks :)

+4  A: 

try this:

$str = preg_replace('{^(<br(\s*/)?>|ANDnbsp;)+}i', '', $str); //from start
$str = preg_replace('{(<br(\s*/)?>|ANDnbsp;)+$}i', '', $str); //from end

that also gets XHTML <br /> and <br/> forms

note: replace "AND" with an ampersand above (can't figure out how to get the software to not turn it into an actual non-breaking space)

Kip
doesn't seem to pick up multiple line breaks
works for me with this: $str = '<br><br>this is a test<br><br>'; Can you give me an example of a string it doesn't work with?
Kip
you are right.. didn't realize my display function was performing nl2br. Thanks!
You probably have to do  
Mark
I had the same problem. Tried   but it preserves the string exactly the same. It seems to be converting   only.
Seb
A: 

With preg_replace:

$str = "<br>some text&nbsp;"
$str = preg_replace('/(^(<br>|&nbsp)*)|((<br>|&nbsp)*$)/i', '', $str);

Didn't test it, but something like that should work.

Seb
I get unknown modifier for /g
I don't think you need /g in PHP...?
Mark
You're right, that's not a search but a replace... I'll change that now, sorry.
Seb