Remove

The code below is from http://www.sitepoint.com/forums/showthread.php?t=719666
I changed space(   ) to underbar(_) for simplification.

[b]code[/b]

<?php

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="mySite.com" class="box" style="color:blue">site</a> 
which is under long  long   long    sleep.';

$myText=retainSpace($myText); 

echo $myText;
?>

The following is the result of the code above.

[b]result[/b]

This_is_my_<a[COLOR="Red"]_[/COLOR]href="mySite.com"[COLOR="red"]_[/COLOR]class="box"[COLOR="red"]_[/COLOR]style="color:blue">site</a>_

which_is_under_long__long___long____sleep.


I like to get my target result below.

[b]target result[/b]

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

which_is_under_long__long___long____sleep.

With your help for making my target result above,

Can I make retainedSpace function working only inside tags without working outside tags?
or
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?