拆分此字符串值的最佳方法是什么?

时间:2020-03-31 00:06:05

标签: php regex datetime explode

字符串值将类似于P0DT0H4M13S

P can be ignored.
0D is the DAY
0H is the HOUR
4M is the MINUTE
13S is the SECOND

做4:13之类的事情会很好。

如果有一天,那么1 DAY 4:13

小时和日期可以是1天4:4:13

我正试图爆炸它,但这似乎很愚蠢,是否存在可以处理此拆分的正则表达式?

谢谢!

2 个答案:

答案 0 :(得分:4)

这是一个PHP DateInterval字符串,应使用该类进行处理。例如:

$str = 'P0DT0H4M13S';

$interval = new DateInterval($str);
$output = '';
if ($interval->d) {
    $output = $interval->format('%d DAY ');
}
$output .= $interval->format('%H:%I:%S');
echo $output;

输出:

00:04:13

Demo on 3v4l.org

很明显,如果需要,可以修改代码以与白天相同的方式跳过小时。

答案 1 :(得分:1)

您可以使用正则表达式

^.(?:([1-9]*)|0)DT(\d+)H(\d+)M(\d+)S\b

具有四个捕获组,分别对应于日期($1),小时,分钟和秒。如果捕获组1匹配(日期大于零),则您所需的字符串是(伪代码)

$1 DAY $2:$3:4$

如果日期为零,则字符串为

$2:$3:4$

Demo

PRCE正则表达式引擎执行以下操作:

^           # match beginning of line
.           # match 1 char 
(?:         # begin non-cap grp
  ([1-9]*)  # match '0'-'9' in capture group 1
  |         # or
  0         # match '0'
)           # end non-cap grp
DT          # match string 
(\d+)H      # match 1+ digits in cap grp 2, then 'H'
(\d+)M      # match 1+ digits in cap grp 3, then 'M'
(\d+)S      # match 1+ digits in cap grp 4, then 'S'
\b          # match word break
相关问题