preg_replace 和 file_get_contents - 如何获取 ${1}?
我有这段代码:
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);
一切都很好(即 !...!
之间的文本被替换为文本本身)。
如何使file_get_contents
中的${1}
也被替换?
I have this piece of code:
echo preg_replace('/\!(.*)\!/', file_get_contents('${1}'), $str);
What it is meant to do is replacing all !...!
with the contents of the file specified between the exclamation marks. However, it is not working because ${1}
is not getting replaced:
Warning: file_get_contents(${1}) [function.file-get-contents]: failed to open stream: No such file or directory
If I code:
echo preg_replace('/\!(.*)\!/', '${1}', $te);
everything is fine (i.e. the text between !...!
is replaced by the text itself).
How can I make the ${1}
in file_get_contents
also be replaced?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就这样吧。使用 preg_replace_callback 进行此类替换,您需要在匹配项上调用自定义函数来提供替换字符串。
There you go. Use preg_replace_callback for this kind of replacements, where you need to call a custom function on the matches that would give the replacement string.
您还可以使用
e
修饰符,如下所示:但就像
eval()
函数一样,在某些情况下这可能会变得邪恶。You could also use the
e
modifiert, like this:But just like the
eval()
function, this might become evil in some cases.