How to catch images with blank dimensions?

Personally, the first thing I would do after matching the attributes is to create an associative array of:

array( 'attribute_name' => 'attribute_value' )

It will make it easier to get the attribute directly than having to search the array and I think overall it will make the code more direct. Since we know that index 0 is our attribute names and index 1 is our attribute values, we can use array_combine() to create the format listed above:

$attributes = array_combine( $img[1], $img[2] );

Finally, we can strip out any empty values from the array by finding the difference and then run the conditional.

$attributes = array_diff( $attributes, array( '""' ) );

Of course the above you would have to refactor your code to account for the new associative array $attributes['src'] and so forth. The problem with your original solution was you were searching for the value in the 1 index where you should have looked in the 2 index( which contains the values ):

if ( # Images with no width/height
    ! in_array( 'width', $img[1] ) || ! in_array( 'height', $img[1] ) ||
    # Images with blank width/height
    ( in_array( 'width', $img[1] ) && in_array( '""', $img[2] ) ) || ( in_array( 'height', $img[1] ) && in_array( '""', $img[2] ) )
) {

Leave a Comment