I'm trying to process some html and replace all img tags src with base64. I've written the function below to convert the image and return it in base64. What I need help with is the following:
I need to use str_replace, preg_replace or some sort regex to scan some html and replace all of the "src" with the base64 representation of the image. The html is stored as a variable and not as an actual html document.For example, if I have some html like:
$htmlSample = "<div>Some text, yada yada and now and image <img src='image1.png' /></div>"
I need to scan it and replace src='image.png' with the base64 equivalent, something like src="data:image/png;base64,/9j/4WvuRXhpZgAASUkqAAgAAAAIAA8BAgASAAAAbgAABAgAK" ---(this is not actual base64 just some filler text). The function will need to be able to do this for multiple images in the html. If you can point me in the right direction I would be very greatful. Thanks guys!
function convertImage($file)
{
if($fp = fopen($file,"rb", 0))
{
$picture = fread($fp,filesize($file));
fclose($fp);
$base64 = base64_encode($picture);
$tag = '<img ' . "" .
'src="data:image/png;base64,' . $base64 .
'" />';
return $tag;
}
}