Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

php - 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... :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...