简体   繁体   English

没有前导 0 PHP 的分钟或秒

[英]Minutes or Seconds without a leading 0 PHP

I am in the midst of changing the dates in my database to something else.我正在将数据库中的日期更改为其他日期。 However, when getting them to convert to the new style, I notice that some of them are missing a leading 0 for the minutes or seconds.但是,当让它们转换为新样式时,我注意到其中一些在几分钟或几秒钟内缺少前导 0。

$origDate = Sat Jan 19 16:15:3 2019

or或者

$origDate = Sat Jan 19 16:8:39 2019

This will fail because its looking for a leading 0. How can I fix this?这将失败,因为它正在寻找前导 0。我该如何解决这个问题?

$oldDate = DateTime::createFromFormat('l M d H:i:s Y', $origDate);
$origDate = $oldDate->format('Y-m-d H:i');

也许这过于简单,但 PHP 已经能够在不使用createFromFormat()情况下自动解析该格式,因此您应该可以使用:

$oldDate = new DateTime($origDate);

You can do that:你可以这样做:

$origDate = 'Sat Jan 19 16:8:39 2019';

$origDate = preg_replace('~:\K\d\b|\b\d(?=:)~', '0$0', $origDate);

echo $origDate;

\\b looks for a word boundary (limit between a digit (or a letter or an underscore) and another character. \\b查找单词边界(数字(或字母或下划线)和另一个字符之间的限制。
\\K changes the position of the match result. \\K改变匹配结果的位置。
(?=..) is a lookahead assertion that checks forward if the subpattern match. (?=..)是一个前瞻断言,它检查子模式是否匹配。 The content matched in the subpattern isn't included in the match result.子模式中匹配的内容不包含在匹配结果中。

Note: I jumped too quickly on my old horse, @Don'tPanic​'s answer is obviously the way to go.注意:我的老马跳得太快了,@Don'tPanic 的回答显然是要走的路。

A slightly simpler regex.一个稍微简单的正则表达式。
Just looking for a single digit without a neighbor.只是寻找一个没有邻居的数字。

$origDate = 'Sat Jan 1 6:8:3 2019';

$origDate = preg_replace("/\b\d{1}\b/", '0$0', $origDate);

echo $origDate; //Sat Jan 01 06:08:03 2019

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM