php - Get all images in a directory except retina

780

I have a php script which grabs all of the images in a set directory. The script works without fault. My issue is that I want it to only get none retina images. All of the retina images are named in the format '[email protected]' whereas all of the regular images are named in the format 'image1.jpg'. With this in mind I want my script to discount any image that contains '@2x' in it's name.

My script is:

<?php
    $directory = 'images/';
    $dh = opendir($directory);
    while (false !== ($filename = readdir($dh)))
    {
        $files[] = $filename;
    };
    $images = preg_grep ('/(\.gif|\.GIF|\.jpg|\.jpeg|\.JPG|\.JPEG|\.png|\.PNG)$/i', $files);

    foreach ($images as $image)
    {
        echo '<img src="'.$directory.$image.'" alt="">';
    }
?>

The problem is I don't have the vocabulary to know what to search for in Google so if anyone could point me in the right direction I would appreciate it. Thanks

52

Answer

Solution:

I would use stripos put this conditional in your foreach loop

if(stripos($image,'@2x') === false){
    echo '<img src="'.$directory.$image.'" alt="">';
}
665

Answer

Solution:

You can make your script a little shorter by using:

$directory = 'images/';

$allImages = glob($directory.'*.{jpg,JPG,jpeg,JPEG,gif,GIF,png,PNG}', GLOB_BRACE);
$nonRetinaImages = preg_grep('/@2x/i', $allImages, PREG_GREP_INVERT);

foreach ($nonRetinaImages as $image)
{
    echo '<img src="'.$image.'" alt="">';
}

People are also looking for solutions to the problem: php - Node insert continues to call nodeapi even if query failed

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.