正则表达式:修改img src标签

时间:2012-10-23 17:05:07

标签: php html regex image

我尝试用内嵌图像(data:image)替换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;
?>

我上传了此测试文件 - &gt; http://goo.gl/vWl9B

1 个答案:

答案 0 :(得分: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];
}