How can I strip the data:image part from a base64 string of any image type in PHP

You can use a regular expression:

$img = preg_replace('#data:image/[^;]+;base64,#', '', $s['image']);

if the text you are replacing is the first text in the image, adding ^ at the beginning of the regexp will make it much faster, because it won't analyze the entire image, just the first few characters:

$img = preg_replace('#^data:image/[^;]+;base64,#', '', $s['image']);

Function file_get_contents remove header and use base64_decode function, so you get clear content image.

Try this code:

$img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA0gA...';
$imageContent = file_get_contents($img);

Tags:

Php

String

Base64