Search code examples
phpregexexplodestripos

I need to check if certain number is in string of numbers


I really need some help with this... i just cant make it work.

For now i have this piece of code and it's working fine. What it does is... retuns all files within a directory according to date in their name.

<?php
header('Access-Control-Allow-Origin: *');
$imagesDir = '';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

$filteredImages = [];
foreach($images as $image) {
    $current_date = date("Ymd");
    $file_date = substr($image, 0, 8);
    if (strcmp($current_date, $file_date)>=0)
        $filteredImages[] = $image;
}
echo json_encode($filteredImages, JSON_UNESCAPED_UNICODE);
?>

But now i need to filter those files (probably before this code is even executed). acording to the string in their name.

files are named in the following manner:

yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.123456789.jpg
yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.9.jpg
yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.458.jpg

i need to filter out only ones that have certain number within that string of numbers at the end (between "." and ".jpg") eg. number 9

$number = 9

i was trying with this piece of code to seperate only that last part of name:

<?php
function getBetween($jpgname,$start,$end){
    $r = explode($start, $jpgname);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}

$jpgname = "yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.12789.jpg";
$start = ".";
$end = ".jpg";
$output = getBetween($jpgname,$start,$end);
echo $output;
?>

and i guess i would need STRIPOS within all of this... but im lost now... :(


Solution

  • You can probably use preg_grep.
    It's regex for arrays.

    This is untested but I think it should work.

    header('Access-Control-Allow-Origin: *');
    $imagesDir = '';
    $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
    
    $find = 9;
    $filtered = preg_grep("/.*?\.\d*" . $find . "\d*\./", $images);
    

    The regex will look for anything to a dot then any number or no number, the $find then any or no number again and a dot again.