首页 > 解决方案 > 检查名称是否以PHP中的字符串结尾

问题描述

在我的文件夹缓存中,我有几十个名称为 的文件filename-number.json,例如

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

我有一个简单的脚本,每 2 小时清理一次缓存目录,删除超过 2 小时的文件:

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

现在,我只希望每 2 小时删除一次编号(在.json文件开头存在编号之前但不是编号)不以 结尾的文件-100.json,并且-100.json仅每 7 天删除一次以 结尾的文件。

我知道我可以用它preg_match()来获取名称,但是有没有有效的方法来执行它?

标签: phppreg-match

解决方案


有比使用 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
}

对于 PHP 7,有几种方法可以模拟它,请查看https://www.php.net/manual/en/function.str-ends-with.php底部


推荐阅读