Division of integers in a String
I have this string the first is the hours, second 开发者_C百科minutes, third seconds.
744:39:46
How do I divide the hours '744' in PHP?
If I'm understanding you correctly, you want to get the substring '744'
from the string '744:39:46'
. Since the latter string always has a particular form, you can simply use the explode
function to split the string by commas and then take the last element:
$str='744:39:46';
$arr=explode(':',$str);
$string_i_want=$arr[0]; //assigns '744' to $string_i_want
You can also pick it out with a regular expression by using preg_match
:
$str='744:39:46';
if(preg_match('/^(\d+):\d+:\d+$/',$str,$matches))
{
$string_i_want=$matches[1]; //assigns '744' to $string_i_want
}
else
{
//The string didn't match...my guess is that something very weird is going on.
}
In the regular expression, \d+
denotes "one or more digits", ^
denotes the beginning of the string, and $
denotes the end of the string. The parentheses around the first \d+
allows for capturing of the first set of digits into $matches[1]
(and $matches[0]
is the entire string--ie $matches[0]===$str
).
$time = "744:39:46";
$timeunits = explode(":", $time);
$hours = $timeunits[0];
print $hours;
Assuming you mean divide it into days,
$hours = 744;
$days = floor($hours / 24);
$hours = $hours % 24;
$parts = explode(":", "744:39:46");
// Divide the hours
echo $parts[0] / $somevalue;
精彩评论