I want to remove all base64 images from a string
<img src="data:image/png;base64,iVBORw0..="><img src="data:image/png;base64,iVBORw1..=">...
and replace them with image1, image2 and so on.
<img src=" image1"><img src=" image2">...
So I am deleting the base64 part of the string and replacing it with "image" followed by the occurrence counter but it's not working so I get image1 all the time.
What can I do? Thanks!!
This is my code so far:
$replacement = "image";
$stringResult= deleteBase64_andReplace("data:", "=", $replacement, $string);
echo $stringResult;
function deleteBase64_andReplace($start, $end, $replacement, $string) {
$count = 0;
$pattern = '|' . preg_quote($start) . '(.*)' . preg_quote($end) . '|U';
while (strpos($string, $start) !== false) {
return preg_replace($pattern, $replacement.++$count, $string);
}
}
You need to replace the
deleteBase64_andReplacefunction withSee the PHP demo. Output is
<img src="image1"><img src="image2">.Notes:
preg_replaceis replaced withpreg_replace_callbackto be able to make changes to$countwhen replacing the subsequent matchespreg_quote($start, '|') . '(.*?)' . preg_quote($end, '|')now escapes the regex delimiter char, you chose|and it needs to be escaped, tooUflag and replace.*with.*?to make the regex more transparent