0

Here is my problem (PHP), i've a String which could be like that :

$var = 'Hello, hello, hello <img src="data:image/png;base64,lkqhdklqbhjdkhlqjshdljhqsdhqslkjhdlqhdjlkqshdjlkhsq"> hello hello <img src="data:image/png;base64,ljshqflhsqjlkfhjqsfjlkqhs"> jhfqflsqjk';

And I would like to convert every base64 image met in var $var. But I've no idea, how can I do that... Especially, a way to cut the string to isolate only img tags.

I just would like to make a function, which take the var $var as argument

$var = 'Hello, hello, hello <img src="data:image/png;base64,lkqhdklqbhjdkhlqjshdljhqsdhqslkjhdlqhdjlkqshdjlkhsq"> hello hello <img src="data:image/png;base64,ljshqflhsqjlkfhjqsfjlkqhs"> jhfqflsqjk';

and gives me :

return "Hello, hello, hello <img src="firstImage.jpg"/> hello hello <img src="secondImage.jpg"/> jhfqflsqjk";

In jpg or png

Undo
  • 25,519
  • 37
  • 106
  • 129
Snooze
  • 197
  • 1
  • 2
  • 10
  • so just use [base64_decode](http://php.net/manual/en/function.base64-decode.php) –  Mar 15 '16 at 19:57
  • 1
    Can you add some details. Do you want to have an array with de decoded value? Show us what do you expect, what did you try.. – olibiaz Mar 15 '16 at 21:05

1 Answers1

1

Here is an example using regular expressions, but if you're parsing a full HTML document, it's better to use DOM to parse the HTML and then you can walk the document processing image tags.

Here is the example with regex:

<?php

$var = 'Hello, hello, hello <img src="data:image/png;base64,lkqhdklqbhjdkhlqjshdljhqsdhqslkjhdlqhdjlkqshdjlkhsq"> hello hello <img src="data:image/png;base64,ljshqflhsqjlkfhjqsfjlkqhs"> jhfqflsqjk';

if ( ($c = preg_match_all('/<img.*?src=(?:\'|")?data:image\/(?:png|jpeg|jpg|gif);base64,([^\'"\s>]+)/i', $var, $matches)) > 0 ) {
    for ($i = 0; $i < $c; ++$i) {
        $data = base64_decode($matches[1][$i]);
        if ($data) {
            // successfully base64 decoded
        }
    }
}

Demo: https://regex101.com/r/vA1tT4/1

This answer might also be helpful. Hope that gets you going.

Community
  • 1
  • 1
drew010
  • 68,777
  • 11
  • 134
  • 162