0

i am using php and wants to extract phone/mobile numbers from string, i have string with multiple format of phone numbers like

$str = '(123) 456-7890 or (123)456-7890 and 1234567890 test "123.456.7890" another test "123 456 7890"';

i had write one RE as,

$phoneMatches = '';
$str = '(123) 456-7890 or (123)456-7890 or 1234567890 or "123.456.7890" or "123 456 7890"';
$phonePattern = '/\b[0-9]{3}\s*[-]?\s*[0-9]{3}\s*[-]?\s*[0-9]{4}\b/';
preg_match_all($phonePattern, $str, $phoneMatches);
echo "<pre>";
print_r($phoneMatches);
exit;

but it gives me output like this,

Array
(
    [0] => Array
        (
            [0] => 1234567890
            [1] => 123 456 7890
        )
)

Means only two, but i want all the possible combination of phone numbers and mobile numbers from string of text by using only ONE Regular expression.

Thanks

Dr Magneto
  • 981
  • 1
  • 8
  • 18

1 Answers1

0

I know I'm late, and I'm not sure if this is what you wanted, but I came up with this solution:

[+()\d].*?\d{4}(?!\d)

Demonstration: regex101.com

Explanation:

  • [+()\d] - We start by matching anything that might represent the start of a phone number.
  • .*?\d{4} - Then we match anything (using a lazy quantifier) until we reach four ending digits. Just a little note: I considered this as a rule, but it might not always apply. You'd then need to modify the regex to include other cases.
  • (?!\d) - This is a negative lookahead and it means that we don't want any matches followed by a digit character. I used this to avoid some half-matches.

Another observation is that this regex doesn't validate any phone number. You could have anything in between the matches, mainly because of this part: .*?\d{4}. This will work depending on what kind of situation you intend to use it.

Pedro Corso
  • 557
  • 8
  • 22