php - 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>
解决方案
如果路径是相对的,如您的示例中那样,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);
推荐阅读
- ruby-on-rails - 登录 JWT 令牌在 localhost 上有效,但在 heroku 上无效——数据错误
- python - 如何使用 python 将 .odt 文件转换为 html
- java - 如果我以编程方式向其添加元素,则 ScrollView 不会滚动
- python - KFold with sklearn.model_selection shuffle 错误
- python - 如何提取像素的ARGB颜色
- arrays - 从以字母开头的列中提取值列表
- php - 标头位置后的PHP做某事
- django - AttributeError: 'NoneType' 对象在尝试使用 Q 过滤器获取最新记录时没有属性 'answer'
- r - 对于每一行,找到最接近指定值的列
- visual-studio - 如何在 Unity 项目中引用外部 DLL 而不将它们提交到存储库中?