Home > Net >  preg_match_all pattern from one array, subject from another
preg_match_all pattern from one array, subject from another

Time:12-21

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

CodePudding user response:

It is not really clear what you are actually trying to achieve, what result you want to create. But this might point you into the right direction:

<?php
$patterns = array_values([
    "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)?)$/',
]);
$subjects = array_values([
    0 => "10,00 % Steuer von",
    1 => "1.650,31",
    2 => "165,03",
]);
$result = [];
for ($i=0; $i<3; $i  ) {
    preg_match($patterns[$i], $subjects[$i], $matches);
    $result[] = $matches[1];
}
print_r($result);

That would be an alternative:

<?php
$data = array_combine(
    [
        0 => "10,00 % Steuer von",
        1 => "1.650,31",
        2 => "165,03",
    ],
    [
        "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)?)$/',
    ]
);
$result = [];
array_walk($data, function($pattern, $subject) use (&$result) {
    preg_match($pattern, $subject, $matches);
    $result[] = $matches[1];    
});
print_r($result);

Both variants create the same output:

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

CodePudding user response:

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