Search code examples
phpregexpcre

Timezones validation regex


I'm trying to validate timezones. Example:

UTC-12
UTC-6:30

So - UTC will stay the same, sign will be alternating(+ or -) and number varies from -12 to +14.

I don't understand why this regex not working (I get not valid):

$val = 'UTC+12';
$range = '-11:30|-11|-10:30|-10|-9:30|-9|-8:30|-8|-7:30|-7|-6:30|-6|-5:30|-5|-4:30|-4|-3:30|-3|-2:30|-2|-1:30|-1|-0:30|\+0|\+0:30|\+1|\+1:30|\+2|\+2:30|\+3|\+3:30|\+4|\+4:30|\+5|\+5:30|\+5:45|\+6|\+6:30|\+7|\+7:30|\+8|\+8:30|\+8:45|\+9|\+9:30|\+10|\+10:30|\+11|\+11:30|\+12|\+12:45|\+13|\+13:45|\+14';

$regex = '/^UTC(\+|-)(' . $range . ')/';

    if(preg_match($regex, $val)){
        echo 'valid';
    }else{
        echo 'not valid';
    }

Solution

  • You need to escape the + symbols in the regex so they are not greedy repeats.

    for example, +8 becomes \+8. Something like this (php isn't my language):

    $val = 'UTC+12'; $range = '-12|-11:30|-11|-10:30|-10|-9:30|-9|-8:30|-8|-7:30|-7|-6:30|-6|-5:30|-5|-4:30|-4|-3:30|-3|-2:30|-2|-1:30|-1|-0:30|+0|+0:30|+1|+1:30|+2|+2:30|+3|+3:30|+4|+4:30|+5|+5:30|+5:45|+6|+6:30|+7|+7:30|+8|+8:30|+8:45|+9|+9:30|+10|+10:30|+11|+11:30|+12|+12:45|+13|+13:45|+14';
    
    $range = str_replace ( '+' , '\+' , $range)
    
    $regex = '/^UTC(' . $range . ')/';
    
        if(preg_match($regex, $val)){
            echo 'valid';
        }else{
            echo 'not valid';
        }