Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to seconds with PHP

Tags:

php

strtotime

I have string '6m15s' in PHP that I would like to convert in to time or ideally seconds. I am using the strtotime() function like:

$time = date('H:i:s', strtotime('6m15s'));
echo $time;

But all I get '01:00:00'. Is this possible to convert my string and if so what would be the best way to do so?

like image 727
ShiggyDooDah Avatar asked Jul 02 '26 01:07

ShiggyDooDah


2 Answers

You could use substr():

$string = '6m15s';
$minute = substr($string, 0, 1);
$second = substr($string, 2, 2);
echo date('H:i:s', strtotime("00:$minute:$second"));
// outputs 00:06:15
like image 145
mister martin Avatar answered Jul 03 '26 15:07

mister martin


If you're trying to get the total number of seconds then something like:

preg_match('/((?<h>[\d]+)h)?((?<m>[\d]+)m)?((?<s>[\d]+)s?)/', $var, $m);

echo ($m['h']* 60 + $m['m']) * 60 + $m['s'];  // 375

This looks for hours as well, as in 1h6m15s.

like image 30
AbraCadaver Avatar answered Jul 03 '26 13:07

AbraCadaver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!