拆分此字符串值的最佳方法是什么?
What is the best way to split this string value up?
字符串值类似于 P0DT0H4M13S
P can be ignored.
0D is the DAY
0H is the HOUR
4M is the MINUTE
13S is the SECOND
做一些像 4:13 这样的事情会很好。
如果有一天那么1天4:13
HOUR AND DAY 可以是 1 DAY 4:4:13
我试图分解它,但这看起来很愚蠢,有没有可以处理这种拆分的正则表达式?
谢谢!
这是一个 PHP DateInterval
字符串,应该使用 class 进行处理。例如:
$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
显然,如果需要,可以修改代码,以与日期相同的方式跳过小时。
您可以使用正则表达式
^.(?:([1-9]*)|0)DT(\d+)H(\d+)M(\d+)S\b
里面有四个捕获组,分别对应天(</code>)、时、分、秒。如果捕获组 1 匹配(日期大于零),则您需要的字符串是(伪代码)</p>
<pre><code> DAY ::4$
如果天为零,则字符串为
::4$
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
字符串值类似于 P0DT0H4M13S
P can be ignored.
0D is the DAY
0H is the HOUR
4M is the MINUTE
13S is the SECOND
做一些像 4:13 这样的事情会很好。
如果有一天那么1天4:13
HOUR AND DAY 可以是 1 DAY 4:4:13
我试图分解它,但这看起来很愚蠢,有没有可以处理这种拆分的正则表达式?
谢谢!
这是一个 PHP DateInterval
字符串,应该使用 class 进行处理。例如:
$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
显然,如果需要,可以修改代码,以与日期相同的方式跳过小时。
您可以使用正则表达式
^.(?:([1-9]*)|0)DT(\d+)H(\d+)M(\d+)S\b
里面有四个捕获组,分别对应天(</code>)、时、分、秒。如果捕获组 1 匹配(日期大于零),则您需要的字符串是(伪代码)</p>
<pre><code> DAY ::4$
如果天为零,则字符串为
::4$
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