我尝试用内联图像(数据:图像)替换 html 文档中的所有图像。我有一个不起作用的示例代码:
function data_uri($filename) {
$mime = mime_content_type($filename);
$data = base64_encode(file_get_contents($filename));
return "data:$mime;base64,$data";
}
function img_handler($matches) {
$image_element = $matches[1];
$pattern = '/(src=["\'])([^"\']+)(["\'])/';
$image_element = preg_replace($pattern, create_function(
$matches,
$matches[1] . data_uri($matches[2]) . $matches[3]),
$image_element);
return $image_element;
}
$content = (many) different img tags
$search = '(<img\s+[^>]+>)';
$content = preg_replace_callback($search, 'img_handler', $content);
有人可以检查此代码吗?谢谢!
更新: (...)警告file_get_contents()[function.file-get-contents]:文件名不能为空(...)
这意味着 src url 不在处理程序中:(
更新 2
<?php
function data_uri($filename) {
$mime = mime_content_type($filename);
$data = base64_encode(file_get_contents($filename));
return "data:$mime;base64,$data";
}
function img_handler($matches) {
$image_element = $matches[0];
$pattern = '/(src=["\'])([^"\']+)(["\'])/';
$image_element = preg_replace_callback($pattern, create_function(
$matchess,
$matchess[1] . data_uri($matchess[2]) . $matchess[3]),
$image_element);
return $image_element;
}
$content = '<a href="http://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Googlelogoi.png/180px-Googlelogoi.png"><img class="alignnone" src="http://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Googlelogoi.png/180px-Googlelogoi.png" alt="google" width="580" height="326" title="google" /></a>';
$search = '(<img\s+[^>]+>)';
$content = preg_replace_callback($search, 'img_handler', $content);
echo $content;
?>
我已经上传了这个测试文件-> http://goo.gl/vWl9B