好像这应该是简单的,但下面的代码不工作:的PHP的preg_replace
$text = preg_replace('/test([0-9]+)/i', $array["$1"], $text);
的代码应该找到,如“test1的”,“TEST2”所有情况下,“ test3'等,并替换$ array [1],$ array [2],$ array [3]等值。
我在做什么错了?
好像这应该是简单的,但下面的代码不工作:的PHP的preg_replace
$text = preg_replace('/test([0-9]+)/i', $array["$1"], $text);
的代码应该找到,如“test1的”,“TEST2”所有情况下,“ test3'等,并替换$ array [1],$ array [2],$ array [3]等值。
我在做什么错了?
你需要使用一个回调:
$text = preg_replace_callback('/(test)([0-9]+)/i',
function($m) use($array) { return $m[1].$array[$m[2]]; },
$text);
该函数将匹配和使用与第二撷取小组赛作为索引数组项串接第一捕获组的比赛。你可能需要一个if在那里检查$array[$m[2]]
是否先存在。
另外,您可以使用一个循环:
foreach($array as $key => $val) {
$text = str_replace("test$key", "test$val", $text);
}
谢谢!辉煌! – Bintz
你已经有答案了。这个只是为了解释你的假设错误。
$1
不是第一参数的结果,它是由preg_replace
本身使用仅的占位符。您的使用也调用命令的优先顺序。
换句话说,如果你试试这个代码:
$text = 'Lorem test8 Dolor';
function test($arg) { echo $arg.PHP_EOL; }
$text = preg_replace('/test([0-9]+)/i', test("$1"), $text);
echo $text;
你得到这样的输出:
$1
Lorem Dolor
正如你所看到的,第一参数计算,然后结果由preg_replace
使用:test()
函数接收从字面上$1
(并以同样的方式你的数组),而不是8
检索由preg_replace
;然后preg_replace
用第二个参数中返回的值替换匹配的子字符串:在上述情况下,test()
不返回任何内容,因此替换为空。
有了这个代码:
function test() { return '[$1]'; }
$text = preg_replace('/test([0-9]+)/i', test(), $text);
结果字符串为:
Lorem [8] Dolor
因为test()
返回[$1]
并且它可以通过preg_replace
被用来执行替换。
$array["$1"] = 'Ipsum';
$text = preg_replace('/test([0-9]+)/i', $array["$1"], $text);
的最后文本是:
在特定情况下,如果你有这样一个场景中仅更换发生
Lorem Ipsum Dolor
这不是你想要的结果,但 - 如前所述 - 你已经有了答案......
您想使用'preg_replace_callback()'并通过'use()'将数组传递给它, – Rizier123
preg_replace的第二个参数需要一个替换字符串,它可以包含$ n形式的引用。这些不是php变量,所以你不能按照你想要的方式使用它们。 – georaldc