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

Profile photo of Kimball

Kimball

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

Leave a Reply

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