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

)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.