如何从字符串中删除结束空白段落?

In my database, some text are stored as

<p>texxxxxxxxxxt1</p>
<p>&nbsp;</p>
<p>textttttttttt2</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>teeeeeeeeeext3</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</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>&nbsp;<\/p>)+$#", '', $content);
$content = preg_replace("#(<p>&nbsp;<\/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>&nbsp;</p>
<p>textttttttttt2</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>teeeeeeeeeext3</p>

thanks in advance!

In case you only have <p>&nbsp;</p> at the end, you can use this:

([
]*<p>&nbsp;<\/p>)*$

Demo: https://regex101.com/r/rS3uY3/1

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>&nbsp;</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>&nbsp;</p>
<p>text2</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>text3</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>";
$substring = "<p>&nbsp;</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);