preg_replace()的意外结果

时间:2014-12-11 20:32:51

标签: php regex preg-replace

$subject = "'foo' = 'bar'";
$pattern = "/('foo' = ').*(')/";
$var = "123baz";
$replacement = "$1$var$2";
print_r(preg_replace($pattern, $replacement, $subject));

结果为23baz'而不是'foo' = '123baz'。为什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

认为你正在寻找类似的东西:

$subject = "'foo' = 'bar'";
$pattern = "/(= ').*(')/";
$var = "123baz";
$replacement = "= '$var'";
print_r(preg_replace($pattern, $replacement, $subject));

输出:

'foo' = '123baz'