How can I check if the fifth and sixth characters are a specific two-digit number?

I want to verify phone numbers. The only valid telephone numbers start as follows: +36 20 | +36 30 | +36 31 | +36 70

My code looks like this, but now you can enter +36 21 or +36 71, which I would like to avoid. How can I check a two-digit number? Like 70 or 30.

$phone = '+36 70 123 4567';

if ( preg_match( '|^\+36 [237][01] [1-9][0-9]{2} [0-9]{2}[0-9]{2}$|', $phone ) ) { 
    echo 'phone number is good';
}

      

+3


source to share


3 answers


If you want very specific numbers:

/^\+36(20|30|31).../

      



Using the set notation ( [237][01]

) will open up too many of the other possibilities you've seen.

+3


source


You can use non-capture groups to specify the values ​​to be allowed:

^\+36 (?:[237]0|31) [1-9][0-9]{2} [0-9]{4}$

      

See regex demo

[237][01]

(two successive character class) corresponds to 2

or 3

, or 7

followed by 0

or 1

, and (?:[237]0|31)

corresponds to either 2

, 3

, 7

and then 0

, or 31

char.



The whole pattern matches:

  • ^

    - start mixing
  • +36

    - +36

    and space
  • (?:[237]0|31)

    - see description above


  • - space
  • [1-9]

    - character class corresponding to one rom digit 1

    - 9

    (excludes 0

    )
  • [0-9]{2}

    - any 2 ASCII digits (from 0

    to 9

    )


  • - space
  • [0-9]{4}

    - 4 digits
  • $

    - end of line.

Note that instead of literal spaces, you can use \s

that matches any space, and to match 1 or 0 occurrences (if empty is optional), you can add ?

(or *

match 0+ occurrences) after \s

- \s?

/ \s*

.

+1


source


$re = '/\+36\s(20|30|31|70)\s.*/';
$str = '+36 20 4145654';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches);

      

Here I used \s

to match all whitespace characters. Of course, you can also use the space character just like this:

$re = '/\+36 (20|30|31|70) .*/';

      

+1


source







All Articles