Search code examples
xmlxsltdocbook

XSLT: Conditionally add Modify Substring


I have a function that adds a zero-width characters. It's not quite working the way I want it to though. How do I get it to add the zero-space character every 15 chars only if it does not contain a normal space?

<xsl:template match="text()[parent::d:entry]">
    <xsl:call-template name="intersperse-with-zero-spaces">
        <xsl:with-param name="str" select="."/>
        <xsl:with-param name="max_length" select="number(15)"/>
    </xsl:call-template>
</xsl:template>
<xsl:template name="intersperse-with-zero-spaces">
        <xsl:param name="str"/>
        <xsl:param name="max_length"/>
        <xsl:variable name="ret">
            <xsl:value-of select="substring($str, 1, $max_length)"/>
            <xsl:if test="string-length($str) &gt; $max_length">
                <xsl:value-of select="'&#x200b;'"/>
                <xsl:call-template name="intersperse-with-zero-spaces">
                    <xsl:with-param name="str" select="substring($str, $max_length + 1)"/>
                    <xsl:with-param name="max_length" select="$max_length"/>
                </xsl:call-template>
            </xsl:if>
        </xsl:variable>
        <xsl:value-of select="$ret"/>
    </xsl:template>

Solution

  • A few hints. First off:

    <xsl:template match="d:entry/text()">
    

    is better than

    <xsl:template match="text()[parent::d:entry]">
    

    And then:

    <xsl:template name="intersperse-with-zero-spaces">
      <xsl:param name="str"/>
      <xsl:param name="max_length"/>
    
      <!-- your variable "ret" is not necessary at all -->
    
      <xsl:variable name="head" select="substring($str, 1, $max_length)" />
      <xsl:variable name="tail" select="substring($str, $max_length + 1)" />
    
      <xsl:value-of select="$head"/>
    
      <!-- the empty string evaluates to false -->
      <xsl:if test="$tail">
        <!-- there's no space present when translate() returns the same string
             and the $tail does not begin with a space, either  -->
        <xsl:if test="
          string-length(translate($head, ' ', '')) = string-length($head)
          and not(substring($tail, 1, 1) = ' ')
        ">
          <xsl:text>&#x200b;</xsl:text>
        </xsl:if>
        <xsl:call-template name="intersperse-with-zero-spaces">
          <xsl:with-param name="str"        select="$tail"/>
          <xsl:with-param name="max_length" select="$max_length"/>
        </xsl:call-template>
      </xsl:if>
    </xsl:template>
    

    Also, I'd probably call the variable $interval, not $max_length. But that's purely cosmetic.