0

我尝试用内联图像(数据:图像)替换 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

4

1 回答 1

3

你的正则表达式没问题。你用create_function()错了。随后内部preg_replace_callback()不起作用。调用data_uri()发生在任何正则表达式替换发生之前,因此出现未定义的文件名错误。

使用适当的回调函数:

$image_element = preg_replace_callback($pattern, "data_uri_callback", $image_element);

然后将您的代码移到那里:

function data_uri_callback($matchess) {
    return  $matchess[1] . data_uri($matchess[2]) . $matchess[3];
}
于 2012-10-23T18:40:34.270 回答