在php中使用preg替换更改时间格式

发布于 2024-08-23 02:47:55 字数 271 浏览 2 评论 0原文

我只是想知道我们是否可以用 preg 替换来做到这一点

,就像如果有时间

1h 38 min

可以更改为

98 mins

2h 20 min

可以更改为

140 mins

或者只是建议我任何其他随机函数,这是更简单的方法,

谢谢

i m just wondering if we can do this with preg replace

like if there's time like

1h 38 min

can change to

98 mins

2h 20 min

can change to

140 mins

or just suggest me any other random function to this is simpler way

thanks

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

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

发布评论

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

评论(3

多像笑话 2024-08-30 02:47:56

这个简单的函数应该可以解决问题。但它不对字符串格式进行验证。

function reformat_time_string($timestr) {
    $vals = sscanf($timestr, "%dh %dm");
    $total_min = ($vals[0] * 60) + $vals[1];
    return "$total_min mins";
}

$timestr = "2h 15m";
echo reformat_time_string($timestr); /* echoes '135 mins' */

This simple function should do the trick. It does no verification on the string format, though.

function reformat_time_string($timestr) {
    $vals = sscanf($timestr, "%dh %dm");
    $total_min = ($vals[0] * 60) + $vals[1];
    return "$total_min mins";
}

$timestr = "2h 15m";
echo reformat_time_string($timestr); /* echoes '135 mins' */
感悟人生的甜 2024-08-30 02:47:56
$str="1h 38 min";
$s = explode(" ",$str);
if ( strpos ( $s[0] ,"h" ) !==FALSE) {
    $hr=str_replace("h","",$s[0]);
    print ($hr*60) + $s[1]."\n";
}
$str="1h 38 min";
$s = explode(" ",$str);
if ( strpos ( $s[0] ,"h" ) !==FALSE) {
    $hr=str_replace("h","",$s[0]);
    print ($hr*60) + $s[1]."\n";
}
‖放下 2024-08-30 02:47:56
$pattern = '!(\d+)\s*h\s*(\d+)\s*min!';
foreach( array('1h 38 min', '2h 20 min') as $input) {
  echo preg_replace_callback($pattern, function($x) { return ($x[1]*60+$x[2]).' minutes'; }, $input), "\n";
}

打印

98 minutes
140 minutes

5.3 之前的 php 版本,您必须使用

function foo($x) {
  return ($x[1]*60+$x[2]).' minutes';
}
$pattern = '!(\d+)\s*h\s*(\d+)\s*min!';
foreach( array('1h 38 min', '2h 20 min') as $input) {
  echo preg_replace_callback($pattern, 'foo', $input), "\n";
}
$pattern = '!(\d+)\s*h\s*(\d+)\s*min!';
foreach( array('1h 38 min', '2h 20 min') as $input) {
  echo preg_replace_callback($pattern, function($x) { return ($x[1]*60+$x[2]).' minutes'; }, $input), "\n";
}

prints

98 minutes
140 minutes

for php versions prior to 5.3 you'd have to use

function foo($x) {
  return ($x[1]*60+$x[2]).' minutes';
}
$pattern = '!(\d+)\s*h\s*(\d+)\s*min!';
foreach( array('1h 38 min', '2h 20 min') as $input) {
  echo preg_replace_callback($pattern, 'foo', $input), "\n";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文