php - 检查名称是否以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()
来获取名称,但是有没有有效的方法来执行它?
解决方案
有比使用 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底部
推荐阅读
- java - 该循环不适用于第二次迭代
- ios - Apple pay:在网络上创建的支付令牌与应用内创建的支付令牌有区别吗?
- azure - 使用 Azure 流分析检测字符串参数的异常
- java - 如何在 Android 上访问 API 17 的联系人
- google-sheets - 如何根据三个水平和垂直标准选择价值?
- dialogflow-es - 在意图之间退出机器人
- linux - 通过半双工接口发送文件
- vue.js - Nuxt + Vue + Vuetify:this.$vuetify.breakpoint 错误地初始化为 'xs'
- python - 基于另一个嵌套列表的元素从嵌套列表中提取元素
- ansible - 在 Playbook 中使用 Ansible 库存 IP