Home > Software design >  Check if name ends by string in PHP
Check if name ends by string in PHP

Time:10-30

In my folder cache, i have dozens of files whose name is filename-number.json, like

sifriugh-80.json
dlifjbhvzique-76.json
dfhgzeiuy-12.json
...

I have a simple script that cleans my cache dir every 2 hours, deleting files older than 2 hours:

$fileSystemIterator = new FilesystemIterator('cache');
$now = time();
foreach ($fileSystemIterator as $file) {
    if ($now - $file->getCTime() >= 3 * 3600) // 2 hours
        unlink('cache/' . $file->getFilename());
}

Now, i'm looking to only delete every 2 hours files whose number (before .json but not if number is present at the beginning of the file) does NOT end by -100.json, and those ending by -100.json, every 7 days only.

I know that i can use preg_match() to get names, but is there any effective way to perform it?

CodePudding user response:

There is much simpler way than regex using PHP 8 str_ends_with() : https://www.php.net/manual/en/function.str-ends-with.php

if (str_ends_with($file->getFilename(), '100.json)) {
    // unlink at needed time
} else {
    // unlink at needed time
}

For PHP 7, there are several ways to emulate it, check at the bottom of https://www.php.net/manual/en/function.str-ends-with.php

CodePudding user response:

I do not see why you should not use preg_match. It is so good here. Before using preg_match you should check the first symbol in file name and skip the next code if it is_numeric. If it is not numeric you need to get only ending "-" can be presented zero or ones number 1 or more digits .json ending (pattern can be something like this /-?\d \.json$/) After that you can parse it and know the real number before .json, Your verification will be something like

If "-" symbol exists and number is 100 check the date for 7 days

If number is not 100 check the date for 2 hours

  • Related