CFLib.org – Common Function Library Project

preg_match_all(regex, str)

Last updated February 15, 2004

author

Aaron Eisenberger

Version: 1 | Requires: CF5 | Library: StrLib

Description:
Searches a string for all matches to the regular expression given and puts them in an array along with any backreferences. After the first match is found, the subsequent searches are continued on from end of the last match.

Return Values:
Returns an array.

Example:

<cfset phones=preg_match_all("[1\-\(]*?(\d{3})?[\-\)\s]*?(\d{3}-\d{4})", "Call 555-1212 or 1-800-555-1212 or (310) 555-1212")>
<cfdump var=#phones#>

Parameters:

Name Description Required
regex Regular expression. Yes
str String to search. Yes

Full UDF Source:

/**
 * Emulates the preg_match_all function in PHP for returning all regex matches along with their backreferences.
 * 
 * @param regex 	 Regular expression. (Required)
 * @param str 	 String to search. (Required)
 * @return Returns an array. 
 * @author Aaron Eisenberger (aaron@x-clothing.com) 
 * @version 1, February 15, 2004 
 */
function preg_match_all(regex,str) {
	var results = arraynew(2);
	var pos = 1;
	var loop = 1;
	var match = "";
	var x= 1;
	
	while (REFind(regex, str, pos)) { 
		match = REFind(regex, str, pos, TRUE); 
		for (x = 1; x lte arrayLen(match.pos); x = x + 1) {
			if(match.len[x])
				results[x][loop] = mid(str, match.pos[x], match.len[x]);
			else
				results[x][loop] = '';
		}
		pos = match.pos[1] + match.len[1];
		loop = loop + 1;
	}
	return results;
}
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