tags:

views:

24

answers:

2

I am using the code below to create an array of images. Id love to be able to NOT add any images with -c.jpg in the filename. Can anyone help get this up and running? I am using PHP 5

<?php
$jsarray = array();
$iterator = new DirectoryIterator(dirname("public/images/portfolio/all/"));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        //filtering to exclude the color images
        $jsarray[] = "'" . $fileinfo->getFilename() . "'";
    }
}
$jsstring = implode(",", $jsarray);
?>
A: 
$jsarray = array();
$iterator = new DirectoryIterator(dirname("public/images/portfolio/all/"));

foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile() && !preg_match('/-c\.jpg$/', $fileinfo->getFilename())) {
        $jsarray[] = "'" . $fileinfo->getFilename() . "'";
    }
}

$jsstring = implode(",", $jsarray);

That’s it.

Joó Ádám
Thanks mate. Perfect.
Andy
A: 
if(strpos($fileinfo->getFilename(), "-c.jpg") === false) {
    $jsarray[] = "'" . $fileinfo->getFilename() . "'";
}

Try that. strpos tells you the position of the search string if it's there, and -1 if it isn't.

Toji
Hmm, the manual says strpos returns FALSE when the needle is not found. You should use '=== FALSE' then. I'd prefer the preg_match solution, as file names *ending* with -c.jpg should be excluded here.
mkluwe
It seems you are right. I swear that I recall using it with -1 in years past, but that was PHP3 era. In any case thanks for the catch, and the answer has been edited to prevent misleading anyone in the future.
Toji