Situation
I am trying to capture an element of a string with a regex. I am trying to retrieve the offset from these strings:
America/Iqaluit (-4:00)
America/Anchorage (-8:00)
These string are passed in a function that is used by the usort() function as so usort($timezones, "sortByTime");
. Here is the code I am using to sort my elements:
function sortByTime($a, $b) {
if(preg_match("/^[A-z]*\/[A-z]* \((-[0-9]:[0-9]{2})\)/", $a, $matches)){
$tz[0] = $matches[1];
}
if(preg_match("/^[A-z]*\/[A-z]* \((-[0-9]:[0-9]{2})\)/", $b, $matches)){
$tz[1] = $matches[1];
}
return $tz[1] - $tz[0];
}
Problem
The preg_match function is not working with the variables $a
and $b
. I tried changing the variable with an inline string and it worked. Here is an example:
preg_match("/^[A-z]*\/[A-z]* \((-[0-9]:[0-9]{2})\)/", $b, $matches); //Doesn't work
preg_match("/^[A-z]*\/[A-z]* \((-[0-9]:[0-9]{2})\)/", "America/Yellowknife (-6:00)", $matches); //Works
Why and how can I fix this issue?
Thank you.
Edit
Please note that the $timezones array has a structure like this:
array(2) {
["America/Adak"]=>
string(21) "America/Adak (-9:00)"
["America/Anchorage"]=>
string(26) "America/Anchorage (-8:00)"
}