how can I trim <br>
from the end of a string?
views:
717answers:
2
+6
A:
$Output = preg_replace('/'.preg_quote('<br>&'.'nbsp;').'$/i', '', $String);
Where $String
is the input and $Output
is the result.
sirlancelot
2009-04-13 07:46:28
Why the string concatenation inside preg_quote, if I may ask?
Joey
2009-04-13 08:00:42
SO doesn't like the entity (replaces with a real non-breaking-space ;)
sirlancelot
2009-04-13 15:58:27
er... why not replace it with ?
R. Bemrose
2009-04-13 19:52:00
sirlancelot
2009-04-13 21:33:40
+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
2009-04-13 19:45:18
An interesting solution, but it will likely break if the needle also appears somewhere in the string, not necessarily at the end.
sirlancelot
2009-04-13 21:48:38
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
2009-04-14 12:32:45