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

PHP实现MikroTik返回的字符串格式运行时长转秒数

解决MikroTik时长字符串转秒数的问题

MikroTik返回的运行时长格式(如2d13m30s、13m30s、30s)属于紧凑的单位拼接格式,strtotime无法直接识别这种无空格的缩写,得自己写解析逻辑处理。

直接用正则匹配提取每个单位对应的数值,再转换成秒数累加,代码如下:

function mikrotikTimeToSeconds($timeStr) {
    $totalSeconds = 0;
    // 匹配所有数字+单位的组合
    preg_match_all('/(\d+)([dhms])/', $timeStr, $matches);

    foreach ($matches[2] as $index => $unit) {
        $amount = (int)$matches[1][$index];
        match($unit) {
            'd' => $totalSeconds += $amount * 86400,
            'h' => $totalSeconds += $amount * 3600,
            'm' => $totalSeconds += $amount * 60,
            's' => $totalSeconds += $amount,
        };
    }

    return $totalSeconds;
}

测试几个典型场景:

// 输出 173610(2天13分30秒的总秒数)
echo mikrotikTimeToSeconds("2d13m30s");

// 输出 810(13分30秒的总秒数)
echo mikrotikTimeToSeconds("13m30s");

// 输出 30
echo mikrotikTimeToSeconds("30s");

之所以strtotime("2h2m30s")不行,是因为它需要单位和数值之间带空格(比如"2h 2m 30s")才能正确识别,而MikroTik返回的格式没有空格,自然解析失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 12:15:40