0

我正在尝试扫描我的内容并用其他东西替换图像源标签(更值得注意的是,支持时的 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()检查),请跳过它

preg_replace()如果有人有建议,我不那么熟悉,我会非常感激。谢谢!

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

4

1 回答 1

0

通常,使用正则表达式解析 HTML 并不是一个好主意,您绝对应该考虑使用其他东西,例如适当的 HTML 解析器。您并不需要 simplehtmldom,它是内置的,DOMDocument并且getElementsByTagName会很好地完成这项工作。

为了解决您当前的问题,这种类型的转换(您希望每个替换都是匹配的任意函数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在完全不相关的上下文中使用占位符,这就是您收到解析错误的原因。

于 2013-04-12T22:40:59.963 回答