You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何判断文件名结尾字符串 按规则清理不同过期时长的缓存文件

最优实现方案

直接用PHP原生字符串判断即可,比preg_match性能高3~10倍,无正则解析开销,代码逻辑也更清晰。

规则梳理

先明确你的清理规则对应逻辑:

  • 文件名以数字开头:不参与-100.json后缀匹配,超过2小时直接清理
  • 文件名不以数字开头:
    • 后缀为-100.json:超过7天再清理
    • 其他后缀:超过2小时清理

另外注意你原代码存在逻辑bug:注释标注是2小时过期,实际判断条件写的是3 * 3600(对应3小时),下方代码已修正。

最终代码

$fileSystemIterator = new FilesystemIterator('cache');
$now = time();
// 提前定义过期阈值,可读性更好
$expire_normal = 2 * 3600; // 普通文件2小时过期
$expire_100 = 7 * 86400; // -100.json后缀文件7天过期

foreach ($fileSystemIterator as $file) {
    $filename = $file->getFilename();
    $threshold = $expire_normal;
    
    // 仅文件名非数字开头的,才判断是否为-100.json后缀
    if (!ctype_digit($filename[0])) {
        // PHP8+ 直接用str_ends_with,性能最优
        if (str_ends_with($filename, '-100.json')) {
            $threshold = $expire_100;
        }
        // 低版本PHP替换为下面的代码
        // if (substr($filename, -9) === '-100.json') {
        //     $threshold = $expire_100;
        // }
    }
    
    // 超过阈值则删除
    if ($now - $file->getCTime() >= $threshold) {
        unlink('cache/' . $filename);
    }
}

性能说明

  • ctype_digit判断首字符是否为数字是O(1)操作,远快于正则匹配
  • str_ends_with/substr判断后缀也是固定长度的字符串比对,没有正则的模式编译、匹配回溯开销,尤其文件量越大优势越明显
  • 完全满足你要求的「匹配.json前的数字为100」的规则,不会出现正则漏匹配、误匹配的问题

内容的提问来源于stack exchange,提问作者CrazyRabbit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 05:24:06