GGGGG
GGGGG

Reputation: 159

regex pattern in php to find phone number between plain text

I am trying to get the phone number between the plain text. But here, I am facing some typical problem. The pattern which I have written is not matching all types of phone numbers. Ex:

$string  = 'sample text sample text sample text (216) 499 1001 sample text sample text (262) 335 60 76-77 sample text sample text sample text';
$string = str_replace('\n', PHP_EOL, $string);
//my regex pattern

$regex = '/(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?\s+?/'; 

preg_match_all($regex, $string, $matches);
print_r($matches);

which is giving me the first phone number , but not the second one. Plz help me in getting that pattern also.

 Output:
    Array
    (
        [0] => Array
            (
                [0] => (216) 499 1001
            ) 
----
---

Thanks in advance!

Upvotes: 0

Views: 398

Answers (1)

Vivian
Vivian

Reputation: 105

Hi I will write the algorithm for this

1) Fetch the whole string into an array 2) start scan document using for loop(till end of line) 3) use is_numeric function finding finding numbers and count total digits then use an if statement (10 digits= phone number, 5 digits=postal code like that) 4) if it is a phone number move the value in to a temp array else next line(use space as separator) 4)now u can process all

if you want to filter phone number with area code or service provider, u can use following codes

<?php
$strings = array('+91', '+11', '+97');
foreach ($strings as $testcase) {
    if (ctype_digit($testcase)) {
        echo "Match found .\n";
    } else {
        echo "Not matching.\n";
    }
}
?>

Upvotes: 1

Related Questions