Возможное решение - может быть, не лучшее - состоит в том, чтобы пройтись через то, что вы сопоставили с 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);
}
}
}
Обратите внимание, что я исправилваш шаблон регулярных выражений.