preg_replace变量替换显示单引号的错误

时间:2017-09-10 14:09:11

标签: php regex preg-replace double-quotes single-quotes

我有preg_replace声明,

$s = "Foo money bar";
echo preg_replace("/(office|rank|money)/i", "<strong>$1</strong>", $s);

返回,

Foo <strong>money</strong> bar 

然而,当我尝试用单引号做同样的事情并且在$i上使用函数时它会中断,

$s = "Foo money bar";
echo preg_replace("/(office|rank|money)/i", '<strong>' . ucfirst($1) . '</strong>', $s);

注意函数的第二个参数中的单引号,现在产生,

syntax error, unexpected '1' (T_LNUMBER), expecting variable (T_VARIABLE) or '{' or '$'

直播示例

Double Quotes

Single Quotes

所以我的问题是为什么会出现这种情况,如何获得预期的输出(强ucfirst),如第二个例子所示?

更新#1

这个问题的发生不仅是因为函数ucfirst,而且由于单引号也是如this示例所示,

$s = "Foo money bar";
echo preg_replace("/(office|rank|money)/i", '<strong>' . $1 . '</strong>', $s);

输出

syntax error, unexpected '1' (T_LNUMBER), expecting variable (T_VARIABLE) or '{' or '$'

2 个答案:

答案 0 :(得分:2)

您无法在preg_replace的第二个参数中使用函数  在搜索之前评估'<strong>' . ucfirst($1) . '</strong>'。要在正则表达式替换中使用函数,必须使用preg_replace_callback:

$result = preg_replace_callback($pattern, function ($m) {
    return '<strong>' . ucfirst($m[1]) . '</strong>';
}, $yourstring);

答案 1 :(得分:1)

你得到的错误不是因为报价的类型,而是因为你是在报价之外做的。

echo preg_replace("/(office|rank|money)/i", "<strong>" . $1 . "</strong>", $s);

这会引发同样的错误。那是因为 $1不是变量,而是back reference。您可以将其称为\1而不是$1,它会更清晰。

因此,您不能引用引号之外的后引用(此外,$1将是非法变量名称)。我不能参考具体的内部结构如何工作(找不到任何东西),但它可能被设置为解释器替换为第n个匹配组的“标志”。

有趣的是,如果你使用函数作为第二个参数将引用包装在引号中,它仍然有效! (从某种意义上说它不会出错。它仍然不会运行该函数。)

<?php
$s = "Foo money bar";
echo preg_replace("/(office|rank|money)/i", '<strong>' . ucfirst('$1') . '</strong>', $s); // works with single and double quotes

Demo

This article没有谈论这个,但无论如何这是一个很好的阅读。