user1756209
user1756209

Reputation: 575

Regex: Modify img src tags

I try to replace all images in a html document with inline image (data:image). I've a sample code which does not work:

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);

Could somebody check this code? Thanks!

UPDATE: (...) Warning file_get_contents() [function.file-get-contents]: Filename cannot be empty (...)

That means the src url is not in the handler :(

UPDATE 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;
?>

I've upload this test file -> http://goo.gl/vWl9B

Upvotes: 0

Views: 1090

Answers (1)

mario
mario

Reputation: 145482

Your regex is alright. You are using create_function() wrong. And subsequently the inner preg_replace_callback() doesn't work. The call to data_uri() happens before any regex-replacement takes place, hencewhy the undefined filename error.

Use a proper callback function:

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

Then move your code into there:

function data_uri_callback($matchess) {
    return  $matchess[1] . data_uri($matchess[2]) . $matchess[3];
}

Upvotes: 3

Related Questions