Php preg_replace在替换中使用匹配的图案

Php preg_replace在替换中使用匹配的图案,php,regex,Php,Regex,我想问一下,是否可以使用匹配的正则表达式模式来确定数组的替换。比如说 $rpl['brat'] = 'qwerty'; $rpl['omri'] = 'asdfgh'; $str1 = 'abc brat bca'; $str2 = 'abc omri bca'; print_r(preg_replace('#bc (.+?) bc#'), $rpl[$1], $str1)); // aqwertya print_r(preg_replace('#bc (.+?) bc#'), $rpl[$

我想问一下,是否可以使用匹配的正则表达式模式来确定数组的替换。比如说

$rpl['brat'] = 'qwerty';
$rpl['omri'] = 'asdfgh';

$str1 = 'abc brat bca';
$str2 = 'abc omri bca';

print_r(preg_replace('#bc (.+?) bc#'), $rpl[$1], $str1)); // aqwertya
print_r(preg_replace('#bc (.+?) bc#'), $rpl[$1], $str2)); // aasdfgha
显然,
$1
的语法不正确,但这只是为了说明我的观点。如何执行此操作?

与修改后的正则表达式一起使用:

$rpl['brat'] = 'qwerty';
$rpl['omri'] = 'asdfgh';

$str1 = 'abc brat bca';
$str2 = 'abc omri bca';

print_r(preg_replace_callback('/bc (\w+) bc/', function($match) use($rpl) {
    return $rpl[$match[1]];
}, $str1)); // => abc qwerty bca

print_r("\n");

print_r(preg_replace_callback('/bc (\w+) bc/', function($match) use($rpl) {
    return $rpl[$match[1]];
}, $str1)); // => aqwertya
输出:

abc qwerty bca
aqwertya

您也可以使用标志“e”,但不建议这样做,因为它可能会导致安全问题

print_r(preg_replace('/bc (.+?) bc/e', '$rpl[$1]', $str1));
print_r(preg_replace('/bc (.+?) bc/e', '$rpl[$1]', $str2));

@德夫努尔因为这一建议而下地狱quickly@YUNOWORK你能带我去吗?@php\u nub\u qq为什么不使用foreach循环呢?@YUNOWORK,因为我不确定是否有这样一个选项(我正在询问的那个)。我可以想出一个解决办法,但如果这是可能的,我宁愿不要,为什么你需要修改regex@php_nub_qq,
(+?)
是无效的正则表达式<代码>+需要前面的模式。我用
\w
匹配任何单词字符。是的,我刚刚看到我漏掉了点,对不起。