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

如何解析省略同起始月的日期范围表达式并拆分日期

日期字段拆分实现方案

问题描述

用户有如下格式的日期字段:

$exampleOne = 'Sep 04-08';
$exampleTwo = 'Sep 29-Oct 01';

需要拆分为如下形式:

$exampleOneResult = {'Sep 04', 'Sep 08'};
$exampleTwoResult = {'Sep 29', 'Oct 01'};

用户原本考虑先按“-”拆分再按空格拆分,但担心资源消耗过大,寻求更优实现方式。

实现方案

方案一:正则表达式一步处理

用正则可以直接匹配两种日期格式,代码更简洁:

function splitDateRange($dateStr) {
    preg_match('/^([A-Za-z]{3} \d{2})-((?:[A-Za-z]{3} )?\d{2})$/', $dateStr, $matches);
    
    $result = [$matches[1]];
    // 第二部分如果没有月份,补上前半段的月份
    $result[] = strpos($matches[2], ' ') !== false ? $matches[2] : substr($matches[1], 0, 4) . $matches[2];
    
    return $result;
}

// 测试示例
$exampleOne = 'Sep 04-08';
$exampleTwo = 'Sep 29-Oct 01';

$exampleOneResult = splitDateRange($exampleOne);
$exampleTwoResult = splitDateRange($exampleTwo);

print_r($exampleOneResult); // 输出:Array ( [0] => Sep 04 [1] => Sep 08 )
print_r($exampleTwoResult); // 输出:Array ( [0] => Sep 29 [1] => Oct 01 )

正则逻辑说明:

  • 第一个捕获组匹配开头的「月份 日期」结构;
  • 第二个捕获组匹配分隔符后的内容,允许带或不带月份;
  • 最后根据第二部分是否含空格判断是否需要补全月份。

方案二:原生字符串处理(性能无压力)

你担心的「按-拆分再按空格拆分」其实完全没必要顾虑性能,这种简单字符串操作的资源消耗可以忽略不计,代码更直观:

function splitDateRange($dateStr) {
    [$firstPart, $secondPart] = explode('-', $dateStr);
    
    // 判断第二部分是否自带月份
    if (strpos($secondPart, ' ') === false) {
        // 提取第一部分的月份前缀(比如「Sep 」)
        $monthPrefix = substr($firstPart, 0, 4);
        $secondPart = $monthPrefix . $secondPart;
    }
    
    return [$firstPart, $secondPart];
}

两种方案都能满足需求,原生字符串处理的代码可读性更高,正则则更紧凑,实际运行性能差异极小,完全不用纠结资源消耗问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 12:27:12