开发者

Timezones validation regex

开发者 https://www.devze.com 2023-03-20 00:50 出处:网络
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'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';
    }


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';
    }


(Posted the solution behalf of the question author to move it into the answer space).

This was so simple. I forgot that I already use signs in my $range array. I don't even have to check for sign inside of my regex.

$regex = '/^UTC(' . $range . ')/';
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号