【问题标题】:preg_replace and file_get_contents - how to get ${1}?preg_replace 和 file_get_contents - 如何获得 ${1}?
【发布时间】:2011-04-09 10:25:54
【问题描述】:

我有这段代码:

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} 也被替换?

【问题讨论】:

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


    【解决方案1】:
    echo preg_replace_callback('/\!(.*)\!/', function($matches) {
        return file_get_contents($matches[1]);
    }, $str);
    

    给你。使用 preg_replace_callback 进行这种替换,您需要在匹配项上调用自定义函数以提供替换字符串。

    【讨论】:

    • 谢谢,不过它会打开!...!。它已被替换,但包括!。不过解决起来很简单,只需使用substr
    • 是的。意识到错误后,我将其编辑为使用$matches[1]
    • 问题:这种语法是否适用于 php 5.3?我问是因为 PHP 5.2.14 不允许将匿名函数直接放入 preg_replace_callback 函数参数列表中,并使用上述代码生成解析错误。 ???
    【解决方案2】:

    您也可以使用e 修饰符,如下所示:

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

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

    【讨论】:

    • 恐怕我不太赞成eval
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 2012-06-22
    相关资源
    最近更新 更多