php - Regex validate and correct telephone number
Get the solution ↓↓↓At the moment I am validating and correcting given Telephone numbers with this version of code:
function validateTelephoneNumber($parameters){
$validTel = "<^((\\+|00)[1-9]\\d{0,3}|0 ?[1-9]|\\(00? ?[1-9][\\d ]*\\))[\\d\\-/ ]*$>";
$telNumber = $parameters;
if (preg_match($validTel, $telNumber)) {
$telNumber = preg_replace("<^\\+>", "00", $telNumber);
$telNumber = preg_replace("<\\D+>", "", $telNumber);
}
return $telNumber;
}
what I want to get is:
| input | return value | comment (only info) |
|
Can you help? Thanks
Answer
Answer
Solution:
The conversion of the telephone number (after validation) can be done in three steps.
Step 1: replace leading zeros with"43"
if the there is no country code.
I assume there is no country code if the string contains exactly one forward slash or begins with a left parenthesis. To add the defautlt country code we can replaces matches of the following regular expression with"43"
.
^(?:\(0*|0*(?=\d+\/\d+$))
Demo 1. PHP's regex engine performs the following operations:
^ : assert beginning of string
(?: : begin non-capture group
\(0* : match '(' followed by 0+ zeroes
| : or
0* : match 0+ zeros
(?= : begin positive lookahead
\d+\/\d+ : match 1+ digits, '/', 0+ digits
$ : assert end of string
) : end positive lookahead
) : end non-capture group
This will convert the strings
0043/2342/213412-1234
+43234 2312341234 12
07234/32434
(0677)32423434
0049 171 12341234
0031 9872 12341234
0043(07234)1234-1234
to
0043/2342/213412-1234
+43234 2312341234 12
437234/32434
43677)32423434
0049 171 12341234
0031 9872 12341234
0043(07234)1234-1234
Step 2: remove unwanted characters
For this step we replace matches of the following regular expression with empty strings.
^0+|[ +\/()-]
Demo 2. PHP's regex engine performs the following operations:
^ : assert beginning of string
0+ : match 1+ zeroes
| : or
[ +\/()-] : match one character in the character class
This will convert the strings obtained in Step 1 to the following.
4323422134121234
43234231234123412
43723432434
4367732423434
4917112341234
31987212341234
430723412341234
Step 3: Add'+'
to the beginning of the string
This is most easily done with a PHP statement, producing the following strings.
+4323422134121234
+43234231234123412
+43723432434
+4367732423434
+4917112341234
+31987212341234
+430723412341234
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: a non well formed numeric value encountered
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.