Search code examples
phparraysregexfiltering

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?


Solution

  • 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 )