在PHP中将数字文字与数组一起使用(preg_replace)

在PHP中将数字文字与数组一起使用(preg_replace),php,arrays,preg-replace,numeric,literals,Php,Arrays,Preg Replace,Numeric,Literals,我尝试在PHP中使用带有preg_replace的数组$test中使用数字文字,我得到了以下结果: $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 pr

我尝试在PHP中使用带有preg_replace的数组$test中使用数字文字,我得到了以下结果:

$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美元,但没有什么仍然工作。。。您能帮我吗?

您可以使用:

通过更多测试:

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";

您当前的用例不需要正则表达式,您可以(并且如果可能的话应该)使用
strtrtr
str\u replace
,具体取决于需求:

$test["a"] = "hey";
$test["b"] = "you";

echo strtr("a b", $test); //hey you

echo str_replace(array_keys($test), array_values($test), "a b"); //hey you
请参阅,了解差异是什么

$test["a"] = "hey";
$test["b"] = "you";

echo strtr("a b", $test); //hey you

echo str_replace(array_keys($test), array_values($test), "a b"); //hey you