Do not apply retainSpace function inside html tag

<?php
 
function retainSpaces($str) {
    $strOut = '';
    for ($i = 0; $i < strlen($str); $i++) {
        $strOut .= ( substr($str, $i, 1) == ' ') ? '&nbsp;' : substr($str, $i, 1);
    }
    return $strOut;
}
 
$strIn_withoutTag = '1 2        3';
 
echo retainSpaces($strIn_withoutTag)."<hr>";

$strIn_withTag = '<span class="color:red">1</span> 2        3';
 
echo retainSpaces($strIn_withTag);
?>

retainSpace function works fine in $strIn_withoutTag, but causes a new problem which is that it puts “nbsp;” to not only normal text but also inside tags.

[b]result of the code above[/b]

1&[COLOR="Blue"]nbsp;[/COLOR]2[COLOR="blue"]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[/COLOR]3<hr>
<span[COLOR="Red"]&nbsp;[/COLOR]class="color:red">1</span>
[COLOR="Blue"]&nbsp;[/COLOR] 2[COLOR="blue"]&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[/COLOR]3

Can I make a function which retains spaces in text, but doesn’t retain space in tags with your help?
or
Can I remove "  which are inside tags only with your help?

$inputString = ‘<span class=“color:red”>1</span> 2 3’;
$outputString = preg_replace_callback(“#[^<]+#”,“relSpaces”,$inputString);

function relSpaces($match){return str_replace(" “,” ",$match[0]);}