如何用数组填充所有preg_match()

时间:2019-03-04 11:10:38

标签: php regex

我有一个字符串"1 + 1 = 12, wrong" 和一个数组[1, 2, 3, 'correct'] 和正则表达式模式/(\d+) + (\d+) = (\d+), (\w+)/

如何将匹配结果填充到数组值。

因此字符串将为"1 + 2 = 3, correct"

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案-可能不是最好的-遍历您与preg_match()匹配的内容,并一一替换。

$str = '1 + 1 = 12, wrong';
$pattern = '/(\d+) \+ (\d+) = (\d+), (\w+)/';
$replacer = [1, 2, 3, 'correct'];
$result = $str;

if (preg_match($pattern, $result, $matches)) {
    // If there is enough matches, we can continue
    if (sizeof($matches) === (sizeof($replacer) + 1)) {
        // We begin at 1 because $matches[0] is the whole string.
        for ($i = 1; $i < sizeof($matches); $i++) {
            // We use preg_replace because str_replace will replace all occurences of the match.
            $result = preg_replace('/' . $matches[$i] . '/', $replacer[$i - 1], $result, 1);
        }
    }
}

请注意,我已更正您的正则表达式模式。