Search code examples
phparraysregexpreg-match-all

preg_match_all pattern from one array, subject from another


I have the following problem where I'm stuck for hours: I have an array with my regex, where I want to match with the subject from another array.

Regex array:

Array
(
    [tax] => /^(\S+\w)/
    [net_amount] => /^((?:[1-9]\d+|\d).(?:[1-9]\d+|\d)(?:\,\d\d)?)$/
    [tax_amount] => /^((?:[1-9]\d+|\d).(?:[1-9]\d+|\d)(?:\,\d\d)?)$/
)

Subject array:

Array
(
    [0] => 10,00 % Steuer von
    [1] => 1.650,31
    [2] => 165,03
)

I don't know how to match these two.

I tried quite things, such as:

foreach($pattern_val as $pattern_k3 => $pattern_val3) {
    $preg_pattern = $pattern_val3;
    foreach($file_content_array[$search_key] as $file_key => $file_value) {
        $preg_value = $file_value;
    }
    preg_match_all($preg_pattern, $preg_value, $matches, PREG_SET_ORDER, 0);
}

With this, I get just the last $preg_value in $matches. I also tried some other methods but none weren't successful.

Would appreciate any hint. Thanks


Solution

  • PHP's preg_replace_callback() accepts arrays for patterns and subjects and you don't need to return a replacement string if you don't want to, leaving you free to do whatever you want inside the callback function. Like appending to a result array you defined beforehand. For example:

    $results = [];
    
    preg_replace_callback($patterns, function ($matches) use (&$results) { 
        $results[] = $matches[1]; // match of the first capturing group
    }, $subjects);
    

    $results for your test data:

    Array
    (
        [0] => 10,00
        [1] => 1.650,31
        [2] => 165,03
    )