解析格式化的日期时间表达式并将数字分配给变量

发布于 2024-11-01 15:23:37 字数 463 浏览 2 评论 0原文

我从 eBay 网络服务获得了这个字符串。

// 2天23小时37分50秒
$字符串 = P2DT23H37M50S

我使用以下代码来提取时间和日期:

$daysLeft = substr($string, 1, 1) 。 “天”;
$hoursLeft = substr($string, 4, 2) 。 “小时”;
$minutesLeft = substr($string, 7, 2) 。 “分钟”;
$secondsLeft = substr($string, 10, 2) 。 “秒”;

但问题是,当小时、分钟和日期只有 1 位数字时,字符串就会变得混乱,我最初可以正常工作,但我有点坚持寻找一种简单的方法来做到这一点,我打算将其写在一堆 If 语句中,但确实想要一种更简单的方法来做到这一点。

I have this string from eBay Web-Service.

// 2Days 23Hours 37Minutes 50Seconds
$string = P2DT23H37M50S

I was using the following code to extract and time and date:

$daysLeft = substr($string, 1, 1) . " Days";
$hoursLeft = substr($string, 4, 2) . " Hours";
$minutesLeft = substr($string, 7, 2) . " Minutes";
$secondsLeft = substr($string, 10, 2) . " Seconds";

But the problem is, When the hours, minutes and dates are only 1 Digit, the strings gets all messed up, I had it working initially, but I'm kind of stuck to find a simple way to do it, I was going to write it in a bunch of If statements, but really want a more simple way to do this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤蝉 2024-11-08 15:23:37

使用 sscanf (与 sprintf 相反)怎么样?

list($daysLeft, $hoursLeft, $minutesLeft, $secondsLeft) = sscanf($string, "P%dDT%dH%dM%DS ");

How about using sscanf (the opposite of sprintf)?

list($daysLeft, $hoursLeft, $minutesLeft, $secondsLeft) = sscanf($string, "P%dDT%dH%dM%DS ");
妄断弥空 2024-11-08 15:23:37

如果现在所有字段始终都在那里,只需将字符串 preg_split 为非数字即可:

$fields = preg_split('[^0-9]+', $string);
$daysLeft = $fields[1] . " Days";
$hoursLeft = $fields[2] . " Hours";
$minutesLeft = $fields[3] . " Minutes";
$secondsLeft = $fields[4] . " Seconds"; 

If you now that all fields always is there, just preg_split the string on non-numbers:

$fields = preg_split('[^0-9]+', $string);
$daysLeft = $fields[1] . " Days";
$hoursLeft = $fields[2] . " Hours";
$minutesLeft = $fields[3] . " Minutes";
$secondsLeft = $fields[4] . " Seconds"; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文