kator
kator

Reputation: 959

Filter a flat array by another flat array containing regex patterns

I have two arrays like this:

$arr1 = ['/^under.*/', '/^develop.*/', '/^repons*/'];
$arr2 = ['understand', 'underconstruction', 'developer', 'develope', 'hide', 'here', 'some'];

I want to match the two arrays and return an array of words starting with the patterns in $arr1.

How do I do this in PHP?

Upvotes: 3

Views: 99

Answers (2)

mickmackusa
mickmackusa

Reputation: 47894

$arr1 is not populated with the most ideal values, so using more performant processes will take additional preparation.

To avoid preparatory processes on $arr1, make looped calls of preg_grep() and merge the results.

Code: (Demo)

var_export(
    array_merge(
        ...array_map(fn($pattern) => preg_grep($pattern, $arr2), $arr1)
    )
);

If you only had an array of literal needles, then you could make iterated str_starts_with() calls inside of array_filter(). (Demo)

$leadingNeedles = ['under', 'develop', 'repons'];
$arr2 = ['understand','underconstruction','developer','develope','hide','here','some'];

var_export(
    array_filter(
        $arr2,
        function ($v) use ($leadingNeedles) {
            foreach ($leadingNeedles as $needle) {
                if (str_starts_with($v, $needle)) {
                    return true;
                }
            }
            return false;
        }
    )
);

If you merely removed your pattern delimiters, you could implode the array of regex patterns with pipes and wrap then entire string in pattern delimiters, then preg_grep() is all you need. (Demo)

$regexes = ['^under.*', '^develop.*', '^repons.*'];
$arr2 = ['understand','underconstruction','developer','develope','hide','here','some'];

var_export(
    preg_grep('/' . implode('|', $regexes) . '/', $arr2)
);

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

This should work for you:

<?php

    $arr1 = array('/^under.*/','/^develop.*/','/^repons*/');
    $arr2 = array('understand','underconstruction','developer','develope','hide','here','some');
    $result = array();

    foreach($arr1 as $pattern) {

        foreach($arr2 as $value) {

            if(preg_match_all($pattern, $value, $matches))
                $result[] = $matches[0][0];
        }

    }

    print_r($result);

?>

Output:

Array ( [0] => understand [1] => underconstruction [2] => developer [3] => develope )

Upvotes: 2

Related Questions