【问题标题】:preg_replace image srcpreg_replace 图像源
【发布时间】:2013-04-13 06:40:59
【问题描述】:

我正在尝试扫描我的内容并用其他东西替换图像源标签(更值得注意的是,支持时的 dataURIs) - 基于我在这里阅读的几个问题,我正在尝试preg_replace()

// Base64 Encodes an image
function wpdu_base64_encode_image($imagefile) {
    $imgtype = array('jpg', 'gif', 'png');
    $filename = file_exists($imagefile) ? htmlentities($imagefile) : die($imagefile.'Image file name does not exist');
    $filetype = pathinfo($filename, PATHINFO_EXTENSION);
    if (in_array($filetype, $imgtype)){
        $imgbinary = fread(fopen($filename, "r"), filesize($filename));
    } else {
        die ('Invalid image type, jpg, gif, and png is only allowed');
    }
    return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}

// Do the do
add_filter('the_content','wpdu_image_replace');
function wpdu_image_replace($content) {
    $upload_dir = wp_upload_dir();
    return preg_replace( '/<img.*src="(.*?)".*?>/', wpdu_base64_encode_image($upload_dir['path'].'/'.\1), $content );
}

我遇到的问题是wpdu_base64_encode_image($upload_dir['path'].'/'.\1),它基本上是在输出preg_replace 结果——目前正在得到:

Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING

$upload_dir['path'] 正在正确输出我需要的图像文件夹的路径,但我也尝试过一些检查但目前还无法实现:

  1. 检查图像源是否是相对的,如果是,则剥离域(目前可以使用site_url() 来完成,我假设它需要是preg_replace()?)
  2. 如果图像甚至不是服务器本地的(再次 - 我假设使用 site_url() 检查),请跳过它

我对@9​​87654331@ 不太熟悉,如果有人有建议,我将不胜感激。谢谢!

编辑:我应该改用http://simplehtmldom.sourceforge.net/ 吗?看起来像一个相当重的锤子,但如果这是一种更可靠的方法,那么我完全赞成 - 以前有人用过吗?

【问题讨论】:

    标签: php preg-replace data-uri


    【解决方案1】:

    一般来说,使用正则表达式解析 HTML 并不是一个好主意,您绝对应该考虑使用其他东西,例如适当的 HTML 解析器。你不太需要 simplehtmldom,内置的 DOMDocumentgetElementsByTagName 可以很好地完成这项工作。

    为了解决您当前的问题,这种类型的转换(您希望每个替换都是匹配的任意函数)是使用preg_replace_callback 完成的:

    $path = $upload_dir['path']; // for brevity
    
    return preg_replace_callback(
        '/<img.*src="(.*?)".*?>/',
        function ($matches) use($path) { 
            return wpdu_base64_encode_image($path.'/'.$matches[1]);
        },
        $content
    );
    

    您当前的代码尝试在完全不相关的上下文中使用占位符 \1,这就是您收到解析错误的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 2014-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      相关资源
      最近更新 更多