Aaron
Aaron

Reputation: 11673

Division of integers in a String

I have this string the first is the hours, second minutes, third seconds.

744:39:46

How do I divide the hours '744' in PHP?

Upvotes: 0

Views: 792

Answers (4)

user554546
user554546

Reputation:

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).

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270637

$parts = explode(":", "744:39:46");
// Divide the hours
echo $parts[0] / $somevalue;

Upvotes: 2

rrehbein
rrehbein

Reputation: 4160

Assuming you mean divide it into days,

$hours = 744;

$days = floor($hours / 24);
$hours = $hours % 24;

Upvotes: 2

torstenvl
torstenvl

Reputation: 785

$time = "744:39:46";
$timeunits = explode(":", $time);
$hours = $timeunits[0];
print $hours;

Upvotes: 2

Related Questions