preg_place语法(Img Src) [英] preg_replace syntax (img src)

查看:85
本文介绍了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 );
}

我有三个问题:

  1. 我使用服务器上的相对路径启动了‘src’标记--但是没有检查是否:
    1. 服务器上确实存在该镜像
    2. 如果图像是相对URL,则URL是否为相对URL
  2. 我的$replacement变量错误(我不确定如何输出仅在src标记中的内容)
  3. 我希望不必在替换中声明<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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆