Project

Profile

Help

Best way to replace characters

Added by Anonymous over 19 years ago

Legacy ID: #2957828 Legacy Poster: Peter Christoph Alexander Bär (f9race)

Hi, as described in another thread on this forum I am looking for an elegant and efficient way to replace a given set of characters in a single string. I could use the replace function, but I'd have to nest it multiple times, which makes the code unreadable, as there are some 7 characters corresponding to as many nesting levels. So, how would you do this? Bärentöter -> Baerentoeter I want all noch-ASCII characters to be replaced, but effectively it would be good enough to replace all German special characters, like so: ä -> ae ö -> oe ü -> ue ß -> ss Ä -> Ae Ö -> Oe Ü -> Ue Thanks! f9race


Replies (2)

RE: Best way to replace characters - Added by Anonymous over 19 years ago

Legacy ID: #2961523 Legacy Poster: Michael Kay (mhkay)

Define a lookup table for the characters: <xsl:variable name="lookup"> <char c="ä">ae</char> <char c="ö">oe</char> etc. Define a key <xsl:key name="c" match="char" use="@c"/> Define a function to split a string into its characters: <xsl:function name="f:split"> <xsl:param name="string"/> <xsl:sequence select="for $x in string-to-unicode($s) return unicode-to-string($x)"/> </xsl:function> Define the replacement function for characters: <xsl:function name="f:replace"> <xsl:param name="char"/> <xsl:sequence select="($lookup/key('c', $char), $char)[1]"/> </xsl:function> Process a string: string-join(for $c in f:split($str) return f:replace($c), "") Michael Kay

RE: Best way to replace characters - Added by Anonymous over 19 years ago

Legacy ID: #2962258 Legacy Poster: Peter Christoph Alexander Bär (f9race)

Thanks a lot for both your replies. (This one and the one pointing me to non-Saxon specific list at Mulberry.com). This is really a much more elegant solution than a manifold nested replace function call! f9race

    (1-2/2)

    Please register to reply