1.2.1031. Regex On Arrays

Avoid using a loop with arrays of regex or values. There are several PHP function which work directly on arrays, and much faster.

preg_grep() is able to extract all matching strings from an array, or non-matching strings. This usually saves a loop over the strings.

preg_filter() is able to extract all strings from an array, matching at least one regex in an array. This usually saves a double loop over the strings and the regex. The trick here is to provide ‘$0’ as replacement, leading preg_filter() to replace the found string by itself.

Finally, preg_replace_callback() an preg_replace_callback_array() are also able to apply an array of regex to an array of strings, and then, apply callbacks to the found values.

<?php

$regexs = ['/ab+c/', '/abd+/', '/abe+/'];
$strings = ['/abbbbc/', '/abd/', '/abeee/'];

// Directly extract all strings that match one regex
foreach($regexs as $regex) {
    $results[] = preg_grep($regex, $strings);
}

// extract all matching regex, by string
foreach($strings as $string) {
    $results[] = preg_filter($regexs, array_fill(0, count($regexs), '$0'), $string);
}

// very slow way to get all the strings that match a regex
foreach($regexs as $regex) {
    foreach($strings as $string) {
        if (preg_match($regex, $string)) {
            $results[] = $string;
        }
    }
}

?>

See also preg_filter.

1.2.1031.1. Suggestions

  • Apply preg_match() to an array of string or regex, via preg_filter() or preg_grep().

  • Apply preg_match() to an array of string or regex, via preg_replace_callback() or preg_replace_callback_array().

1.2.1031.2. Specs

Short name

Performances/RegexOnArrays

Rulesets

All, Changed Behavior, Performances

Exakat since

1.8.4

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

regex

Available in

Entreprise Edition, Exakat Cloud