preg_replace syntax (img src)(preg_place语法(Img Src))
本文介绍了preg_place语法(Img Src)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试找到一种方法来定位页面上的所有图像,并根据需要修改它们的源。以下是我到目前为止的情况:
add_filter('the_content','wpdu_image_replace');
function wpdu_image_replace($content) {
$upload_dir = wp_upload_dir();
$pattern = '/<img.*src="(.*?)".*?>/';
$replacement = wpdu_base64_encode_image($upload_dir['path'].'/'.1);
return preg_replace( $pattern, $replacement , $content );
}
我有三个问题:
- 我使用服务器上的相对路径启动了‘src’标记--但是没有检查是否:
- 服务器上确实存在该镜像
- 如果图像是相对URL,则URL是否为相对URL
- 我的
$replacement变量错误(我不确定如何输出仅在src标记中的内容) - 我希望不必在替换中声明
<img>标记,因为这样会丢失它周围的所有其他内容(如类、ID等)。
有没有人知道如何抓取图像的来源,并以我描述的方式替换它?我考虑过将Simple HTML DOM作为替代方案--但是得到了糟糕的性能结果。任何帮助都将不胜感激。谢谢!
推荐答案
1)检查服务器上是否确实存在该镜像
preg_match_all("!(?<=src=").+(?="(s|/>))!",$html, $match, PREG_SET_ORDER);
$files = $match;
foreach ($files as $file) {
if (file_exists($file)) {
echo "The file $file exists";
//if image exists you can replace it like:
$html = str_replace($file, 'NewImagePath', $html);//$file is the found image source
} else {
echo "The file $file does not exist";
}
}
替换图像的另一种方式:
$html = '<img id="brandLogo" src="chrome://branding/content/about-logo.png" alt=""/>'
$html = preg_replace('!(?<=src=").+(?="(s|/>))!', 'newlogo.png',$html );
此代码查找源chrome://branding/content/about-logo.png并将其替换为新的newlogo.png
2)要检查路径是相对路径还是绝对路径,可以使用php函数parse_url
这篇关于preg_place语法(Img Src)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:preg_place语法(Img Src)
基础教程推荐
猜你喜欢
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
