Home >Backend Development >PHP Tutorial >php后向引用怎么带入到函数参数

php后向引用怎么带入到函数参数

WBOY
WBOYOriginal
2016-06-23 13:35:551133browse

preg_replace('/{get_(\w+)}/',$arr[$1], $content);


$1为后向引用,我需要把匹配的 \w+ 作为参数,传入到自定义函数,或者作为数组的索引,该怎么实现呢


回复讨论(解决方案)

preg_replace_callback 可以回调函数,但是怎么把匹配到的,作为数组的索引,这个我找不到方法

preg_replace('/{get_(\w+)}/e','$arr["$1"]', $content);

$content = '{get_abc}';$arr['abc'] = 123;echo preg_replace('/{get_(\w+)}/e', '$arr["$1"]', $content);

扩展模式 e 表示 eval,表示将第二个参数当做 php 语句来执行
不过这种做法到了 php5.5 就废止了,因为动态解释 php 语句存在效率和安全的问题

合理的做法是使用 preg_replace_callback
下面开列 3 中写法
$content = '{get_abc}';$arr['abc'] = 123;echo preg_replace_callback('/{get_(\w+)}/', 'back', $content);function back($m) {  global $arr;  return $arr[$m[1]];}
$content = '{get_abc}';$arr['abc'] = 123;echo preg_replace_callback('/{get_(\w+)}/', create_function('$m', 'global $arr; return $arr["$m[1]"];'), $content);
$content = '{get_abc}';$arr['abc'] = 123;echo preg_replace_callback('/{get_(\w+)}/', function($m) use($arr) { return $arr["$m[1]"];}, $content);
显然第 3 种写法最清晰,但只在 php5.3 才开始支持

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn