使用捕获的组作为数组索引的php preg_replace

使用捕获的组作为数组索引的php preg_replace,php,arrays,regex,Php,Arrays,Regex,看起来这应该很简单,但以下代码不起作用: $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',

看起来这应该很简单,但以下代码不起作用:

$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);
}

你已经有答案了。这只是为了更好地解释你的假设错误

$1
不是第一个参数的结果,它是由
preg\u replace
本身使用的占位符。您的使用还将调用命令优先级

换句话说,如果您尝试以下代码:

$text = 'Lorem test8 Dolor';
function test( $arg ) { echo $arg.PHP_EOL; }
$text = preg_replace('/test([0-9]+)/i', test("$1"), $text);
echo $text;
function test() { return '[$1]'; }
$text = preg_replace('/test([0-9]+)/i', test(), $text);
您将获得以下输出:

$1
Lorem  Dolor
如您所见,首先计算参数,然后结果由
preg\u replace
使用:
test()
函数按字面意思接收
$1
(与数组的方式相同),而不是
preg\u replace
检索的
8
;然后,
preg\u replace
用第二个参数中返回的值替换匹配的子字符串:在上述情况下,
test()
不返回任何内容,因此替换内容为“无”

使用此代码:

$text = 'Lorem test8 Dolor';
function test( $arg ) { echo $arg.PHP_EOL; }
$text = preg_replace('/test([0-9]+)/i', test("$1"), $text);
echo $text;
function test() { return '[$1]'; }
$text = preg_replace('/test([0-9]+)/i', test(), $text);
结果字符串为:

Lorem [8] Dolor
因为
test()
返回
[$1]
,并且它可以被
preg\u replace
用来执行替换

在您的特定情况下,仅当您有如下场景时,才会发生替换:

$array["$1"] = 'Ipsum';
$text = preg_replace('/test([0-9]+)/i', $array["$1"], $text);
最后案文是:

Lorem Ipsum Dolor

这不是您想要的结果,但是-如前所述-您已经得到了答案…

您想要使用
preg\u replace\u callback()
并通过
use()
将数组传递给它,preg\u replace的第二个参数接受替换字符串,该字符串可以包含$n形式的引用。这些不是php变量,所以您不能按您想要的方式使用它们。谢谢!明亮的我不知道发生了什么事。请您解释一下,
$m
是什么意思,
$m[1]。$array[$m[2]]
是什么意思?$m是一个匹配数组,因此$m[1]是来自第一个捕获组的匹配()