首页 > 解决方案 > file_get_content 可以与 preg_replace 一起使用吗?

问题描述

如何从 preg_replace 获取文件内容?

<?php

function get($it) {
$r = array("~<script src='(.*?)'></script>~");
$w = array("<script type='text/javascript'>' . file_get_contents($1) . '</script>");
$it = preg_replace($r, $w, $it);
return $it;
}

$it = "<script src='/script.js'></script>";
echo get($it);

?>

它返回<script type='text/javascript'>' . file_get_contents(/script.js) . '</script>

标签: php

解决方案


如果路径是相对的,如您的示例中那样,file_get_contents则将不起作用,但这应该让您更接近:

function get($it) {
    return preg_replace_callback("~<script src='(.*?)'></script>~", function($match){
        return "<script type='text/javascript'>" . file_get_contents($match[1]) . '</script>';
    }, $it);
}
$it = "<script src='/script.js'></script>";
echo get($it);

推荐阅读