Wednesday 15 July 2015

php - Simple regex trying to extract 3 or 4 numbers from "dirty" time string -



php - Simple regex trying to extract 3 or 4 numbers from "dirty" time string -

despite help before on still floundering in regex problems , in array problems.

i trying allow users set time in 205pm 1405 14:05 2.05 pm , on.

previously had times stored 14:05 (standard mysql time format) users not liking if convert 2:05 pm then, when updated values entered (in similar format), breaks database.

i have no problem going 14:05 2:05 pm having nightmare going in opposite direction.

i have fudged things bit cascading if statement string length have spent literally hours trying @ output.

ie if 2-05 pm, start off want 205.

here atrocious code:

if ($_post['xxx']='yyy') { $stuff=$_post['stuff']; $regex='/^\d\d*\d\d*\d\d*\d\d*\d\d*$/'; if (preg_match($regex, $stuff, $matches)) {echo " more 4 digits. cannot time."; } else{ $regex='/^\d\d*\d\d*\d\d*\d\d*$/'; if (preg_match($regex, $stuff, $matches)) {echo " >>4 digits";} else{ $regex='/^\d\d*\d\d*\d\d*$/'; if (preg_match($regex, $stuff, $matches)) {echo " >>3 digits";} else{ $regex='/^\d\d*\d\d*$/'; if (preg_match($regex, $stuff, $matches)) {echo " less 3 digits. cannot time.";} } } } } debug ($matches,"mat1"); $newmatches = implode($matches); debug ($matches,"matn1"); preg_match_all('!\d+!', $newmatches, $matches); debug ($matches,"mat2"); $matches = implode($matches); debug ($matches,"mat3"); echo "<br> matches $matches"; /// hoped digits here ?>

thanks help.

$times = array( '205pm', '1405', '4:05', '2.05 pm' ); foreach($times $time) { // parsing string array 'h' - hour, 'm' - minutes , 'ap' keys preg_match('/(?p<h>\d{1,2})\d?(?p<m>\d{2})\s*(?p<ap>(a|p)m)?/i', $time, $matches); // construction below not necessary, removes values array $matches = array_intersect_key($matches, array_flip(array_filter(array_keys($matches), 'is_string'))); // output result var_dump($matches); }

if using string @ strtotime easier reformat right format, this

$times = array( '205pm', '1405', '4:05', '2.05 pm' ); var_dump(preg_replace('/(\d{1,2})\d?(\d{2})(\s*(a|p)m)?/i', '$1:$2$3', $times));

ps: more complex possible situations suggest reformat time , this, otherwise regexp can nightmare..

$times = array( '9 pm', '205pm', '1405', '4:05', '2.05 pm' ); $times = preg_replace('/(\d{1,2})\d?(\d{2})(\s*(a|p)m)?/i', '$1:$2$3', $times); foreach($times $time) { $date = strtotime($time); if ($date === false) { echo 'unable parse time ' . $time . "\n"; continue; } $hour = date('g', $date); $minutes = date('i', $date); echo $hour . " : " . $minutes . "\n"; }

php regex

No comments:

Post a Comment