简体   繁体   中英

Breaking down phone number in array using regular expression and php

+91 9231665828  +91 9231665828
+91-9231675067  +91-9231675067
+919231665794   +919231665794
91 9231675653   91 9231675653
91-9231675067   91-9231675067
919231665794    919231665794
0 9231675653    0 9231675653
0-9231665808    0-9231665808
09231665808     09231665808

I have this kind of phone number set I want to break down those number in an array Like:

Array
(
    [0] => +91 9231665828
    [1] => +91-9231675067
    [2] => +919231665794
    [3] => 91 9231675653
    [4] => 91-9231675067
    [5] => 919231665794
    [6] => 0 9231675653
    [7] => 0-9231665808
    [8] => 09231665808
    [9] => +91 9231665828
    [10] => +91-9231675067
    [11] => +919231665794
    [12] => 91 9231675653
    [13] => 91-9231675067
    [14] => 919231665794
    [15] => 0 9231675653
    [16] => 0-9231665808
    [17] => 09231665808
)

I write some regular expression but not working.

/\\n|\\s(?=(\\+91(?:-|\\s|)|91(?:-|\\s|)|0(?:-|\\s|))?[7-9][0-9]{9}$)/

I want correct regular expression.

Why not be more general and keep it simple?

\+?\d+[ -]?\d+

This matches all of your sample "phone numbers" and will break the string into an array. However, if you want to validate the numbers that's a different RegEx.


Example/test:

<?php

$string = "+91 9231665828 +91 9231665828
+91-9231675067  +91-9231675067
+919231665794   +919231665794
91 9231675653   91 9231675653
91-9231675067   91-9231675067
919231665794    919231665794
0 9231675653    0 9231675653
0-9231665808    0-9231665808
09231665808  09231665808";

if(preg_match_all('/\+?\d+[ -]?\d+/', $string, $matches))
{
    echo '<pre>';
    print_r($matches[0]);
    echo '</pre>';
}

?>

results in:

Array
(
    [0] => +91 9231665828
    [1] => +91 9231665828
    [2] => +91-9231675067
    [3] => +91-9231675067
    [4] => +919231665794
    [5] => +919231665794
    [6] => 91 9231675653
    [7] => 91 9231675653
    [8] => 91-9231675067
    [9] => 91-9231675067
    [10] => 919231665794
    [11] => 919231665794
    [12] => 0 9231675653
    [13] => 0 9231675653
    [14] => 0-9231665808
    [15] => 0-9231665808
    [16] => 09231665808
    [17] => 09231665808
)

use this pattern ^(\\+?\\d+[ -]?\\d+) notice the anchor ^
Demo

I agree with tenub that validation is a separate task here. But you do need to make sure the engine knows where one number ends and another begins:

\+?\b\d{1,2}[ -]?\d{9,10}\b

Edit: I don't know the significance of the duplicate numbers, but if you only want the first one from each line you can throw a ^ at the beginning of the pattern:

^\+?\b\d{1,2}[ -]?\d{9,10}\b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM