Avikarsha Saha Avikarsha Saha - 5 months ago 13
PHP Question

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.

Answer

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
)
Comments