我正在尝试在 PHP 中将数字文字与我的数组 $test 和 preg_replace 一起使用,这就是我得到的:
$test["a"] = "hey";
// Find a as $0
echo preg_replace("/[a-z]/", "Found:$0", "a")."\n";
// Can replace it by "hey"
echo preg_replace("/[a-z]/", $test['a'], "a")."\n";
// Can't replace it :/
echo preg_replace("/[a-z]/", $test["$0"], "a")."\n";
如您所见,最后一个 preg_replace 函数不起作用,而另外两个函数则工作正常...我尝试了很多次使用各种技巧来包含 $0,但仍然不起作用...你能帮我吗,请问?
最佳答案
您可以使用preg_replace_callback()
:
echo preg_replace_callback("/[a-z]/", function ($b) use ($test) {
return $test[$b[0]];
}, "a")."\n";
进行更多测试:
echo preg_replace_callback("/[a-z]/", function ($b) use ($test) {
if (isset($b[0]) && isset($test[$b[0]]))
return $test[$b[0]];
return "";
}, "a")."\n";
关于php - 在 PHP 中将数字文字与数组一起使用 (preg_replace),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48719912/