You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中file_get_contents能否与preg_replace搭配使用?

问题原因

  • 原代码中preg_replace的第二个替换参数是普通字符串,PHP只会将占位符$1替换为匹配到的路径内容,不会执行字符串中嵌套的file_get_contents函数,因此函数会被直接当作文本输出。
  • 原代码的字符串拼接逻辑也存在错误,在双引号包裹的字符串里写.拼接符不会被识别为PHP语法,反而会直接输出为普通字符。

正确实现方案

推荐使用preg_replace_callback处理动态替换逻辑,这是PHP官方推荐的方案,兼容所有当前支持的PHP版本,避免使用已被高版本PHP移除的/e修饰符。

示例代码

<?php
function get($it) {
    // 正则可适配单双引号的src属性写法
    $pattern = "~<script\s+src=(['"])(.*?)\1></script>~";
    $it = preg_replace_callback($pattern, function ($matches) {
        $jsPath = $matches[2];
        // 提前判断文件存在且可读,避免抛出警告
        if (!is_file($jsPath) || !is_readable($jsPath)) {
            // 读取失败时返回原标签,不影响原有功能
            return $matches[0];
        }
        $jsContent = file_get_contents($jsPath);
        // 转义JS内容中的script结束标签,防止打断HTML结构
        $jsContent = str_replace('</script>', '<\/script>', $jsContent);
        return "<script type='text/javascript'>{$jsContent}</script>";
    }, $it);
    return $it;
}

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

注意事项

  • 注意相对路径和绝对路径的解析规则,确保file_get_contents可以正确定位到JS文件
  • 如果需要引入外部域名的JS资源,需确保PHP配置中allow_url_fopen已开启
  • 如果JS内容存在特殊字符需要额外处理,可根据业务场景补充转义逻辑

内容的提问来源于stack exchange,提问作者SYSA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 13:54:02