Jump to content

Help Separating Time format


Hovanessb

Recommended Posts

Hello i was having trouble creating an array with regex. I have an excel sheet with various time formats including: 1h 51m 10.5s, 51m, 10m 10.5s, 5s and I need to convert the time down to minutes.

Currently my regex is as follows and does not work: /(([0-9]{1,2})h)?(([0-9]{1,2})m)?(([0-9]{1,2}\.[0-9]{0,2})s)?/

Cold any one help a noob out, Im trying to separate each segment in to an array's cell so i can manipulate it later.

 

My code for the entire function is as follows:

public function convertToMinutes($subject) {
 //Regular Expression to remove text
 $pattern = '/(([0-9]{1,2})h)?(([0-9]{1,2})m)?(([0-9]{1,2}\.[0-9]{0,2})s)?/';
 $numbers = preg_split($pattern, $subject);
 if (empty($numbers)) {
  $this -> _flash('warning');
  $return['errors'][] = __(sprintf('Regular Expression is wrong'), true);
 } else {
   //There are only hours, minutes and seconds
  if (count($numbers) == 3) {
   $totalMinutes = 0;
   $hourMinutes = $numbers[0];
   $minutes = $numbers[1];
   $secondMinutes = $numbers[2];
   $totalMinutes = $hourMinutes / 60;
   $totalMinutes = $totalMinutes + ($secondMinutes * 60);
   $totalMinutes = $totalMinutes + ($minutes);
   return $totalMinutes;
   debug(count($numbers));
  } 
  // There is only minutes and seconds
  elseif (count($numbers) == 2) {
   $totalMinutes = 0;
   $minutes = $numbers[0];
   $secondMinutes = $numbers[1];
   $totalMinutes = $totalMinutes + ($secondMinutes * 60);
   $totalMinutes = $totalMinutes + ($minutes);
   return $totalMinutes;debug(count($numbers));
  } else {
   //Return the minutes
   return $numbers[0];
  }
 }


}

Link to comment
https://forums.phpfreaks.com/topic/272827-help-separating-time-format/
Share on other sites

All the... the things. The number+letter bits. The pieces of time.

preg_match_all('/(\d+(?:\.\d*)?)(\D)/', "10m 10.5s", $matches, PREG_SET_ORDER) && print_r($matches);

Array
(
    [0] => Array
        (
            [0] => 10m
            [1] => 10
            [2] => m
        )

    [1] => Array
        (
            [0] => 10.5s
            [1] => 10.5
            [2] => s
        )

)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.