Skip to content

Instantly share code, notes, and snippets.

@xpathr
Created May 10, 2012 14:42
Show Gist options
  • Select an option

  • Save xpathr/2653567 to your computer and use it in GitHub Desktop.

Select an option

Save xpathr/2653567 to your computer and use it in GitHub Desktop.
Substring Count by phoque
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!--
Example Call
<xsl:call-template name="substring-count">
<xsl:with-param name="haystack" select="'the quick brown fox jumps over the lazy dog'" />
<xsl:with-param name="needle" select="'the'" />
</xsl:call-template>
Will return "2".
-->
<xsl:template name="substring-count">
<xsl:param name="haystack"/>
<xsl:param name="needle"/>
<xsl:choose>
<xsl:when test="contains($haystack, $needle) and $haystack and $needle">
<xsl:variable name="count">
<xsl:call-template name="substring-count">
<xsl:with-param name="haystack" select="substring-after($haystack, $needle)"/>
<xsl:with-param name="needle" select="$needle"/>
</xsl:call-template>
</xsl:variable>
<xsl:value-of select="$count + 1"/>
</xsl:when>
<xsl:otherwise>0</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment