Strip img src from posted php screenshots

Look for some regex based help! You have already searched the site and did not find solutions that still apply to my case.

I have a form that is shown to users, one of the text areas is the screenshot area. Currently, the screenshot data is being entered into the database, but since this is starting to make the database quite large, I decided to create a custom image for each inserted screenshot as it would take up less space than the space made in the database.

The problem I am facing is taking a screenshot of the img src etc. and successfully save the data to an image file that can be opened correctly.

Inserted screenshot data is inserted into the database as shown below:

<img src="data:image/png;base64,_BASE_64_DATA_HERE"><br> 

      

Any ideas when posting this data on how to remove unneeded elements and just leave the base64 data behind, creating a saved PNG image?

I currently have this, which doesn't quite work for me, just creating an image that can't be opened:

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($screenshot);
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $screenshot));

file_put_contents('screenshots/screens.png', $data);

      

$screenshot

is the inserted data.

+3


source to share


1 answer


I can suggest removing the start of the anchor ^

and using preg_match

with \K

to crop everything to Base64 images to be written with a pattern of [^"<]*

0 or more chars than "

and <

(it could possibly even be boiled down to [^"]*

):

preg_match('#data:image/\w+;base64,\K[^"<]*#i', '<img src="data:image/png;base64,_BASE_64_DATA_HERE"><br>', $match);
echo $match[0]; // => _BASE_64_DATA_HERE

      



See IDEONE demo

+1


source







All Articles