CFLib.org – Common Function Library Project

preg_match_all(regex, str)

Last updated February 16, 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;
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson