Hovanessb Posted January 8, 2013 Share Posted January 8, 2013 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]; } } } Quote Link to comment Share on other sites More sharing options...
requinix Posted January 8, 2013 Share Posted January 8, 2013 Could just do a preg_match_all() on /(\d+(?:\.\d*)?)(\D)/ (to grab all the $1=number $2=interval) Quote Link to comment Share on other sites More sharing options...
Hovanessb Posted January 8, 2013 Author Share Posted January 8, 2013 (edited) Could just do a preg_match_all() on /(\d+(?:\.\d*)?)(\D)/ (to grab all the $1=number $2=interval) To grab all the what? Edited January 8, 2013 by Hovanessb Quote Link to comment Share on other sites More sharing options...
requinix Posted January 8, 2013 Share Posted January 8, 2013 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 ) ) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.