首页 > 解决方案 > 如何用数组填充所有 preg_match()

问题描述

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

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

所以字符串将是"1 + 2 = 3, correct"

标签: phpregex

解决方案


一个可能的解决方案 - 也许不是最好的- 是循环遍历您匹配的内容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);
        }
    }
}

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


推荐阅读