The rouine is pretty good, however it causes my app to hang, so I needed to add the case:
<xsl:when test="$text = '' or $replace = ''or not($replace)" >
<xsl:value-of select="$text" />
<!-- Prevent thsi routine from hanging -->
</xsl:when>
before the function gets called recursively.
I got the answer from here: When test hanging in an infinite loop
Thank you!