【问题标题】:preg_replace syntax (img src)preg_replace 语法 (img src)
【发布时间】:2012-06-15 14:44:45
【问题描述】:

我正在尝试找到一种方法来定位页面上的所有图像并根据需要修改它们的来源。这是我目前所拥有的:

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 是否是相对的
  2. 我的$replacement 变量错误(我不确定如何输出仅在 src 标记中的内容)
  3. 我希望不必在替换中声明 &lt;img&gt; 标记,因为那样我会丢失它周围的所有其他内容(如类、ID 等)。

有谁知道如何获取图像的来源并以我所描述的方式替换它?我已经将Simple HTML DOM 视为替代方案——但得到了可怕的性能结果。任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: php preg-replace


    【解决方案1】:

    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

    【讨论】:

    • html 中存在多个&lt;img src=""&gt; 并且想用不同的源替换它时如何做到这一点?
    • 在 preg_replace 中的替换参数可以是一个数组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2018-10-02
    相关资源
    最近更新 更多