CFLib.org – Common Function Library Project

preg_match(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.

Return Values:
Returns an array.

Example:

<cfset domain=preg_match("([^\.\/]+)\.([^\.\/]+$)", cgi.server_name)>
<cfdump var="#domain#">

Parameters:

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

Full UDF Source:

/**
 * Emulates the preg_match function in PHP for returning a regex match along with any 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(regex,str) {
    var results = arraynew(1);
    var match = "";
    var x = 1;
    if (REFind(regex, str, 1)) { 
        match = REFind(regex, str, 1, TRUE); 
        for (x = 1; x lte arrayLen(match.pos); x = x + 1) {
            if(match.len[x])
                results[x] = mid(str, match.pos[x], match.len[x]);
            else
                results[x] = '';
        }
    }
    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