The code below is from
I changed space(   ) to underbar(_) for simplification.



function retainSpace($str) {
    $strOut = '';
    for ($i = 0; $i < strlen($str); $i++) {
        $strOut .= ( substr($str, $i, 1) == ' ') ? '_' : substr($str, $i, 1);
    return $strOut;

$myText='This is my <a href="" class="box" style="color:blue">site</a> 
which is under long  long   long    sleep.';


echo $myText;

The following is the result of the code above.




I like to get my target result below.

[b]target result[/b]

This_is_my_<a href="" class="box" style="color:blue">site</a>_


With your help for making my target result above,

Can I make retainedSpace function working only inside tags without working outside tags?
Can I change only the underBar() which is inside a tag to another character like -, = , etc, without chaning the underBar() which is outside a tag?