In my database, some text are stored as
<p>texxxxxxxxxxt1</p>
<p> </p>
<p>textttttttttt2</p>
<p> </p>
<p> </p>
<p>teeeeeeeeeext3</p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
when i'm displaying them, i'd like those final blanks to be removed... I've already tried many things but none of them is working... I thought about
$content = preg_replace("#(<p> <\/p>)+$#", '', $content);
$content = preg_replace("#(<p> <\/p>)+$#", '', $content);
and others but they doesn't work because of the line break... any idea? end result should be something like
<p>texxxxxxxxxxt1</p>
<p> </p>
<p>textttttttttt2</p>
<p> </p>
<p> </p>
<p>teeeeeeeeeext3</p>
thanks in advance!
In case you only have <p> </p>
at the end, you can use this:
([
]*<p> <\/p>)*$
How about breaking the string into an array (on newlines), and then looping from the back of the array. If it is equal to <p> </p>
, then pop it off the array. Finally join the array back into a string.
Here a recursive function:
<?php
$str = "<p>text1</p>
<p> </p>
<p>text2</p>
<p> </p>
<p> </p>
<p>text3</p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>";
$substring = "<p> </p>";
function magic($str, $substring) {
$str = trim(rtrim($str));
if (substr($str, (strlen($str) - strlen($substring)), strlen($str)) == $substring) {
$str = trim(rtrim(substr($str, 0, strlen($str) - strlen($substring))));
$str = magic($str, $substring);
}
return $str;
}
echo magic($str, $substring);