[英]preg_replace image src
我试图浏览我的内容并将图像源标签替换为其他内容(尤其是在受支持时为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)
的问题是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/吗? 似乎是一把沉重的锤子,但是如果那是一种更可靠的方法,那么我全力以赴-以前有人用过吗?
通常,用正则表达式解析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
,这就是为什么会出现解析错误的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.