views:

113

answers:

5
// create a string
$string = '+7';

// try to match the beginning of the string
if(preg_match("{-15 to +12}", $string))
    {
    // if it matches we echo this line
    return {strip all the + sign}
    echo 'its a valid gmt time';
    }
else
    {
    echo 'not valid gmt time';
    }

Question:

  1. please see the first {} on preg_match, is how can we do that ? im new on regex and i just dont know where to start

  2. on the second {} can we somehow strip the + sign by useing regex ?

  3. is the gmt range is right ? -14 to +12 ( well thats what i see on http://www.php.net/manual/en/timezones.others.php )

Thanks

+1  A: 

Here ya go:

  1. //match 0-15 with a +,- in front.

    if(preg_match("/(+|-)([0-9]|1[1-5])/", $string)){
          //match process here 
    }
    

That would match your -15,+12 I would imagine.

  1. To strip out all the {+} signs.

    //take out + and replace with + $newString = str_replace(array("+"),"", $oldString);

Chris
A: 

The regexp could be:

/\+?[0-9]|\+?1[0-2]|\-[1-9]|\-1[0-5]/

This would match 0..12, +0..+12, -1..-15
If the + sign is required, use the RegExp without the ?.

then just do a str_replace on the number:

$number = str_relace('+', '', $number);
levu
there are two + which one ?
btw it doesnt return true if 10 11 or +10 +11 , -10 -11 ( two decimals. ) im trying it on http://gskinner.com/RegExr/
+1  A: 

I would do :

preg_match("/^([+-]\d+)/", $string, $m);
if(isset($m[1]) && $m[1] > -16 && $m[1] < 13) {
    echo 'its a valid gmt time';
} else {
    echo 'not valid gmt time';
}
M42
hmm dont know but it does give me an Undefined offset: 1 on line 2
Adam Ramadhan
Just test the result of preg_match or test if(isset($m[1])) ...
M42
+2  A: 
function validGMT($input)
{
    $gmt = '/^(?:\+?(?:[0]?[0-9]|[1][0-2])|-(?:[0][0-9]|[1][0-4]))$/';
    if ( preg_match( $gmt, $input ) )
    {
        return true;
    }
    else
    {
        return false;
    }       
}

edit*

ive just notice that if you are at php5.2. do this

$val='-2';
$options['options']['min_range'] = -14;
$options['options']['max_range'] = 12; 
$var1 = filter_var($val, FILTER_VALIDATE_INT,$options);
var_dump($var1);   
Adam Ramadhan
`[0]` can be expressed with just `0`.
Gumbo
Gumbo can you explain it more ? +1
Adam Ramadhan
@Adam Ramadhan: `[…]` means *one of the characters expressed with `…`*. Now if “`…`” is just a single character like in this case `0`, it is more comprehensive to just write `0` instead of `[0]`.
Gumbo
example ? btw @adam ive just notice that 44 works too, please check again :|
ok ive edit it. use that instead. but it have to be a 01 not an 1, still cant figure it out.
Adam Ramadhan
+1  A: 
$string = '+7';
if (in_array($string, range(-15, 12))) {
    echo 'its a valid gmt time';
} else {
    echo 'not valid gmt time';
}
GZipp
tested and works great :)
Adam Ramadhan