Author:
phoque
Version:
1.0
Release Date:
6 Nov 2009
Category:
String Operations

Description

Counts substrings in a value-string.

To count elements (lets say <a href>s in your text fields) you should use count(text/*/a) instead.

XSLT

View Raw
<?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>

Discuss this XSLT Utility

Symphony • Open Source XSLT CMS

Server Requirements

  • PHP 5.3-5.6 or 7.0-7.3
  • PHP's LibXML module, with the XSLT extension enabled (--with-xsl)
  • MySQL 5.5 or above
  • An Apache or Litespeed webserver
  • Apache's mod_rewrite module or equivalent

Compatible Hosts

Sign in

Login details