I needed a simple function to use in a TrailsNH Bot to find the largest image in an HTML5 srcset. Here’s what I came up with.
function getLargestImage($srcsetString){ $images = array(); // split on comma $srcsetArray = explode(",", $srcsetString); foreach($srcsetArray as $srcString){ // split on whitespace - optional descriptor $imgArray = explode(" ", trim($srcString)); // cast w or x descriptor as an Integer $images[(int)$imgArray[1]] = $imgArray[0]; } // find the max $maxIndex = max(array_keys($images)); return $images[$maxIndex]; }
This works, although users should bear in mind that any original image is considered a 1x source, and in theory all those in the srcset could be below this; hence the original src may be largest for an img or picture element (in practice, this is very unlikely).
Thanks for pointing that out Laurence. I’ll consider revising the function include the original image as well.