此代码返回错误 preg_replace_callback():需要参数2,'Array'才能成为有效的回调
$tPattern = array(
"/\\\(\d{1,3})/",
"/\\\\\(/",
"/\\\\\)/"
);
$tCallback = array(
function($m) { return chr(octdec($m[1])); },
function($m) { return '('; },
function($m) { return ')'; }
);
return preg_replace_callback($tPattern, $tCallback, $s);
我已将其替换为
$s = preg_replace_callback("/\\\(\d{1,3})/", function($m) { return chr(octdec($m[1])); }, $s);
$s = preg_replace_callback("/\\\\\(/", function($m) { return '('; }, $s);
$s = preg_replace_callback("/\\\\\)/", function($m) { return ')'; }, $s);
return $s;
但我想知道如何使用数组而不是3调用preg_replace_callback?
感谢的
答案 0 :(得分:1)
可悲的是preg_replace_callback
不允许你将回调提供为数组(如str_replace(array, array, $s)
ie),所以你必须遍历回调并在那里进行函数调用
$result = $s;
foreach ($tCallback as $key=>$callback) {
$result = preg_replace_callback($tPattern[$key], $tCallback[$key], $result);
}
return $result;
如果您正在运行PHP7,则可以将preg_replace_callback()
as Misyaath Mohammed suggested与array_combine()
结合使用
$patterns_and_callbacks = array_combine($tPattern, $tCallback);
return preg_replace_callback_array($patterns_and_callbacks, $s);
答案 1 :(得分:1)
你可以使用这个
<?php
$subject = 'Aaaaaa Bbb';
preg_replace_callback_array(
[
'~[a]+~i' => function ($match) {
echo strlen($match[0]), ' matches for "a" found', PHP_EOL;
},
'~[b]+~i' => function ($match) {
echo strlen($match[0]), ' matches for "b" found', PHP_EOL;
}
],
$subject
);
?>
如果找到匹配项,将返回新主题,否则主题将保持不变。