preg_replace和file_get_contents - 如何获得$ {1}?

时间:2011-04-09 10:25:54

标签: php regex replace preg-replace file-get-contents

我有这段代码:

echo preg_replace('/\!(.*)\!/', file_get_contents('${1}'), $str);

它的意图是用感叹号之间指定的文件内容替换所有!...!。但是,它无法正常工作,因为${1}未被替换:

Warning: file_get_contents(${1}) [function.file-get-contents]: failed to open stream: No such file or directory

如果我编码:

echo preg_replace('/\!(.*)\!/', '${1}', $te);

一切都很好(即!...!之间的文字被文本本身取代)。

如何更换${1}中的file_get_contents

2 个答案:

答案 0 :(得分:1)

echo preg_replace_callback('/\!(.*)\!/', function($matches) {
    return file_get_contents($matches[1]);
}, $str);

你去吧。使用preg_replace_callback进行此类替换,您需要在匹配项上调用自定义函数来提供替换字符串。

答案 1 :(得分:0)

你也可以使用e modifiert,如下所示:

echo preg_replace('/!(.*)!/e', 'file_get_contents("$1");', $str);

但就像eval()函数一样,在某些情况下,这可能会成为 evil

相关问题