Question

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)"
}
Was it helpful?

Solution

It looks like you have 2 spaces in your timezones, so:

/^[A-z]*\/[A-z]*  \((-[0-9]:[0-9]{2})\)/
// or
/^[A-z]*\/[A-z]*\s*\((-[0-9]:[0-9]{2})\)/

If you're just interested in the time a partial match might be better:

/\(([-+][0-9]{1,2}:[0-9]{2})\)$/

OTHER TIPS

Try it: /^\w+\/\w+ \((-?\d:[\d]{2})\)/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top