Monday, November 19, 2018

searching for and replacing base64 image string with php




I have an HTML string that am getting from the database. The string has several base64 images that i need to replace with an image file which am supposed to generate from the base64 image string. I have no idea how i can do this. Any pointers will be highly appreciated.



original html





intended html





Answer



echo preg_replace_callback('#((?!src=)[^>])*?src=")data:image/(gif|png|jpeg);base64,([\w=+/]++)("[^>]*>)#', "data_to_img", $content);

function data_to_img($match) {
list(, $img, $type, $base64, $end) = $match;

$bin = base64_decode($base64);
$md5 = md5($bin); // generate a new temporary filename
$fn = "tmp/img/$md5.$type";
file_exists($fn) or file_put_contents($fn, $bin);


return "$img$fn$end"; // new tag
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...