Mono.WTF
Mono.WTF

Reputation: 1597

php - regex to extract phone numbers from a string

i am having a small problem with my regex which i use to extract italian phone numbers from a string

<?php
$output = "+39 3331111111";
preg_match_all('/^((00|\+)39[\. ]??)??3\d{2}[\. ]??\d{6,7}$/',$output,$matches);
echo '<pre>';
print_r($matches[0]);
?>

it works correctly if the $output is just the telephone number but if i change the output with a more complex string like:

(eg. $output = "hello this is my number +39 3331111111 how are you?";)

it will not extract the number, how can i change my regex to extract the number?

Upvotes: 1

Views: 1566

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

Remove the anchors and add word boundaries \b at the right places:

((\b00|\+)39[\. ]??)??3\d{2}[\. ]??\d{6,7}\b
   ^                                       ^

See regex demo.

See IDEONE demo:

$output = "hello this is my number +39 3331111111 how are you?";
preg_match_all('/((\b00|\+)39[\. ]??)??3\d{2}[\. ]??\d{6,7}\b/',$output,$matches);
echo '<pre>';
print_r($matches[0]);

You can also use non-capturing groups (to "clean" the output a bit) and a greedy ? instead of lazy ?? (the regex will be a bit more efficient):

(?:(?:\b00|\+)39[\. ]?)?3\d{2}[\. ]?\d{6,7}\b
 ^^ ^^               ^ ^           ^

See another regex demo

Upvotes: 3

Related Questions