tags:

views:

717

answers:

2

how can I trim <br>&nbsp; from the end of a string?

+6  A: 
$Output = preg_replace('/'.preg_quote('<br>&'.'nbsp;').'$/i', '', $String);

Where $String is the input and $Output is the result.

sirlancelot
Why the string concatenation inside preg_quote, if I may ask?
Joey
SO doesn't like the   entity (replaces with a real non-breaking-space ;)
sirlancelot
er... why not replace it with   ?
R. Bemrose
sirlancelot
+1  A: 

Slightly faster, if what you are trimming is constant:

$haystack = "blah blah blah <br>&"."nbsp;";
$needle = "<br>&"."nbsp;";
echo substr($haystack, 0, strrpos($haystack, $needle));
Jeff Ober
An interesting solution, but it will likely break if the needle also appears somewhere in the string, not necessarily at the end.
sirlancelot
That is true. I've updated the solution to use strrpos instead of strpos, which searches from the end of the string instead.
Jeff Ober