1

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

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Note that to get a match only you can omit the capture groups, you don't have to escape the space and matching 1-3 digits can be shortened to [0-9]{1,3} like ^\+[0-9]{1,3} ?[0-9]{10}$ See regex101.com/r/2zxwZo/1
Yeah you're right. But i've been trying to solve this by his/her own knowledge

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.