我正在尝试扫描我的内容并用其他东西替换图像源标签(更值得注意的是,支持时的 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']
正在正确输出我需要的图像文件夹的路径,但还有一些我已经尝试过但目前还无法实现的检查:
- 检查图像源是否是相对的,如果是,则剥离域(目前可以这样做
site_url()
,我假设需要是的preg_replace()
?) - 如果图像甚至不是服务器本地的(再次 - 我假设使用
site_url()
检查),请跳过它
preg_replace()
如果有人有建议,我不那么熟悉,我会非常感激。谢谢!
编辑:我应该改用http://simplehtmldom.sourceforge.net/吗?看起来像一个相当重的锤子,但如果这是一种更可靠的方法,那么我完全赞成 - 有人以前用过吗?