Parsing HTML5 IMG srcset

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

}

Published by

Kimball

Kimball is a website designer and developer in Goffstown, NH.

2 comments on:
“Parsing HTML5 IMG srcset”

  1. 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).

    1. Thanks for pointing that out Laurence. I’ll consider revising the function include the original image as well.

Leave a Reply

Your email address will not be published. Required fields are marked *