Search code examples
phppreg-replacestrpos

Delete string between strings and replace with text plus counter


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

    }
    
}

Solution

  • You need to replace the deleteBase64_andReplace function with

    function deleteBase64_andReplace($start, $end, $replacement, $string) {
        $count = 0;
        $pattern = '|' . preg_quote($start, '|') . '(.*?)' . preg_quote($end, '|') . '|s'; 
        while (strpos($string, $start) !== false) { 
            return preg_replace_callback($pattern, function($m) use ($replacement, &$count) {
                return $replacement . ++$count;}, $string); 
        }
    }
    

    See the PHP demo. Output is <img src="image1"><img src="image2">.

    Notes:

    • preg_replace is replaced with preg_replace_callback to be able to make changes to $count when replacing the subsequent matches
    • preg_quote($start, '|') . '(.*?)' . preg_quote($end, '|') now escapes the regex delimiter char, you chose | and it needs to be escaped, too
    • I suggest omitting U flag and replace .* with .*? to make the regex more transparent