Reputation: 33
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) |
|-----------------------------------|-----------------------------------|-----------------------------|
| 0043/2342/213412-1234 | +4323422134121234 | |
| +43 234 2312341234 12 | +43234231234123412 | |
| 07234/32434 | +43723432434 |if no country prefix -> +43 |
| (0677)32423434 | +4367732423434 |if no country prefix -> +43 |
| 0049 171 12341234 | +4917112341234 | |
| 0031 9872 12341234 | +31987212341234 | |
| 0043(07234)1234-1234 | +43723412341234 |remove 0 in local prefix |
Can you help? Thanks
Upvotes: 0
Views: 104
Reputation: 110755
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
Upvotes: 1