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

PHP如何用正则或更优方案将多格式时长字符串转换为秒数?

PHP多格式时长转秒实现方案

方案1:正则匹配实现(适配你列出的所有格式)

直接用可选分组的正则捕获小时、分钟、秒三个部分,不存在的部分默认按0计算即可:

function durationToSeconds(string $duration): int
{
    // 匹配可选的时、分、秒部分,忽略空白字符
    preg_match('/(?:(?<h>\d+) h)?\s*(?:(?<m>\d+) min)?\s*(?:(?<s>\d+) sec)?/', $duration, $matches);
    $h = (int)($matches['h'] ?? 0);
    $m = (int)($matches['m'] ?? 0);
    $s = (int)($matches['s'] ?? 0);
    return $h * 3600 + $m * 60 + $s;
}

测试用例结果:

  • durationToSeconds('12 sec') 返回 12
  • durationToSeconds('75 sec') 返回 75
  • durationToSeconds('2 min') 返回 120
  • durationToSeconds('69 min') 返回 4140
  • durationToSeconds('1 h') 返回 3600
  • durationToSeconds('2 h 35 min') 返回 9300

方案2:拆分遍历实现(扩展性更强)

如果后续可能新增其他时间单位(比如天d),用拆分遍历的方式可读性和扩展性更好:

function durationToSeconds(string $duration): int
{
    $unitMap = [
        'h' => 3600,
        'min' => 60,
        'sec' => 1
    ];
    $parts = preg_split('/\s+/', trim($duration));
    $total = 0;
    for ($i = 0; $i < count($parts); $i += 2) {
        $value = (int)$parts[$i];
        $unit = $parts[$i + 1] ?? '';
        if (isset($unitMap[$unit])) {
            $total += $value * $unitMap[$unit];
        }
    }
    return $total;
}

两种方案都可以完全覆盖你列出的所有时长格式,按需选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:18:04