PHP正则表达式输出转换
我想将 12h 34m 45s 这样的输出转换为 12:34:45 ,
如果其中一个返回为空,则应该可以忽略它。 因此,34m 45s 应该是 00:34:45,当然,个位数应该是可能的,例如 1h 4m 1s,以及个位数和两位数的组合,例如 12h 4m 12s 等等。
有人可以帮忙吗?
这是实际的代码
$van = $_POST['gespreksduur_van']; $tot = $_POST['gespreksduur_tot']; $regex = '/(\d\d?h ?)?(\d\d?m ?)?(\d\d?s)?/';
if(preg_match($regex, $van, $match) AND preg_match($regex, $tot, $matches))
{
for ($n = 1; $n <= 3; ++$n) { if (!array_key_exists($n, $match)) $match[$n] = 0; }
for ($i = 1; $i <= 3; ++$i) { if (!array_key_exists($i, $matches)) $matches[$i] = 0; }
$van = printf("%02d:%02d:%02d", $matches[1], $matches[2], $matches[3]);
$tot = printf("%02d:%02d:%02d", $match[1], $match[2], $match[3]);
print($van);
print($tot);
$data['gespreksduurvan'] = htmlspecialchars($van);
$data['gespreksduurtot'] = htmlspecialchars($tot);
$smarty->assign('gsv',$data['gespreksduurvan']);
$smarty->assign('gst',$data['gespreksduurtot']);
}
I want to turn a output like 12h 34m 45s to 12:34:45
also it should be possible if one o these is returned empty is will ignore it.
So 34m 45s should be 00:34:45 and off course single digits should bee possible like 1h 4m 1s and a combo off single and double digits like 12h 4m 12s and so on.
Can someone please help ?
This is the actual code
$van = $_POST['gespreksduur_van'];
$tot = $_POST['gespreksduur_tot'];
$regex = '/(\d\d?h ?)?(\d\d?m ?)?(\d\d?s)?/';
if(preg_match($regex, $van, $match) AND preg_match($regex, $tot, $matches))
{
for ($n = 1; $n <= 3; ++$n) { if (!array_key_exists($n, $match)) $match[$n] = 0; }
for ($i = 1; $i <= 3; ++$i) { if (!array_key_exists($i, $matches)) $matches[$i] = 0; }
$van = printf("%02d:%02d:%02d", $matches[1], $matches[2], $matches[3]);
$tot = printf("%02d:%02d:%02d", $match[1], $match[2], $match[3]);
print($van);
print($tot);
$data['gespreksduurvan'] = htmlspecialchars($van);
$data['gespreksduurtot'] = htmlspecialchars($tot);
$smarty->assign('gsv',$data['gespreksduurvan']);
$smarty->assign('gst',$data['gespreksduurtot']);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用正则表达式提取组件,然后使用
printf()
按照您喜欢的方式格式化组件:正则表达式允许可选组件。 for 循环只是用默认值零填充任何丢失的键(以防止秒或分钟/秒都丢失时出现未定义的键错误)。 printf 总是打印所有带有两个零的组件。
You can use a regex to extract the components, and then a
printf()
to format the components how you like:The regex allows optional components. The for loop there just fills any missing keys with a default value of zero (to prevent undefined key errors when seconds, or both minutes/seconds are missing). The printf always prints all components with two zeros.
如果你想使用正则表达式,你可以使用 preg_replace_callback
If you want to use regex, you can use preg_replace_callback
这是无需正则表达式即可执行此操作的方法
此输出
this is how you can do this without regex
This outputs
像这样的东西吗?
Something like this?