CFLib.org – Common Function Library Project

getTagContentAll(tag, str)

Last updated October 24, 2008

author

Todd Sharp

Version: 1 | Requires: CF5 | Library: StrLib

Description:
Based on getTagContent, this UDF will extract all occurrences of a given tag pair from a string (getTagContent only returns a single occurrence of the tag) and return the individual occurrences as elements in an array. If the tag is not found the UDF will return an empty array.

Return Values:
Returns an array.

Example:

<cfhttp method="get" url="http://cfsilence.com" resolveurl="yes">
<cfset importedContent = cfhttp.fileContent>

<cfdump var="#getTagContentAll("code",importedContent)#">

Parameters:

Name Description Required
tag Tag to look for. Do not include brackets. Yes
str String to parse. Yes

Full UDF Source:

/**
 * Extract all occurrences of a given tag pair from a string.
 * 
 * @param tag 	 Tag to look for. Do not include brackets. (Required)
 * @param str 	 String to parse. (Required)
 * @return Returns an array. 
 * @author Todd Sharp (todd@cfsilence.com) 
 * @version 1, October 24, 2008 
 */
function getTagContentAll(tag,str) {
	var matchStruct = structNew();
	var matchPos = "";
	var matchLen = "";
	var startTag = "<#lcase(tag)#";
	var endTag = "</#tag#>";
	var endTagStart = 0;
	var firstOcc = REFindNoCase(startTag,str,1,true);
	var returnArray = ArrayNew(1);

	//check the char following the tag - if it closes the tag then set the startTag accordingly
	if(mid(str, firstOcc.pos[1]+len(startTag),1) eq ">") {
		startTag = "<#tag#>";
	} else {
	//there are attributes so the RE should accommodate
	//include a space following the tag name so that searching
	//for 'b' does not find 'b' and 'body', etc
	startTag = "<#tag# [^>]*>";
	}

	matchStruct = REFindNoCase(startTag,str,1,"true");
	matchPos = matchStruct.pos [1];
	matchLen = matchStruct.len[1];
	
	if(matchLen eq 0) return returnArray;
	endTagStart = REFindNoCase(endTag,str,matchPos,"false");
	//if no end tag exists return out
	if(endTagStart eq 0) return returnArray;

	ArrayAppend(returnArray,Mid(str,matchPos+matchLen,endTagStart-matchPos-matchLen));

	while (matchLen neq 0) {
		matchStruct = REFindNoCase(startTag,str,matchPos+matchLen,"true");
		matchPos = matchStruct.pos [1];
		matchLen = matchStruct.len[1];
		if(matchLen eq 0) return returnArray;
		endTagStart = REFindNoCase(endTag,str,matchPos,"false");
		ArrayAppend(returnArray,Mid(str,matchPos+matchLen,endTagStart-matchPos-matchLen));
	}

	return returnArray;
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson