cypher
cypher

Reputation: 11

How to format mobile phone number with country code using regex

I have been trying to format properly the phone number so that all country can use at least. I am trying to use this format to accept as many regions as possible Here is my pattern

$pattern = '^\+[0-9]?()[0-9](\s|\S)(\d[0-9]{9})$^'; 

the pattern matches well these formats but once I add a country code with 3 digits and space, it fails

+441213315000
+1 2323214316
+2923432432432

I would like to match this format

+225 0546568022

Upvotes: 1

Views: 632

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Use

^\+[0-9]{1,3} ?[0-9]{10}$

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  \+                       '+'
--------------------------------------------------------------------------------
  [0-9]{1,3}               any character of: '0' to '9' (between 1
                           and 3 times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
   ?                       ' ' (optional (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  [0-9]{10}                any character of: '0' to '9' (10 times)
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

PHP:

preg_match('/^\+[0-9]{1,3} ?[0-9]{10}$/', $string)

JavaScript:

/^\+[0-9]{1,3} ?[0-9]{10}$/.test(string)

Upvotes: 2

FMoosavi
FMoosavi

Reputation: 150

Unlike our friend. I tried to fix your own pattern:

^\+([0-9][0-9]?[0-9]?)(\ )?([0-9]{10})$

Note that i've removed the ^ from end of pattern because it represents start of a new line!

This guy is your friend: https://regex101.com/

Good luck

Upvotes: 1

Related Questions