1

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?

Mono.WTF
  • 1,587
  • 3
  • 18
  • 28
  • Possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – hjpotter92 Nov 04 '15 at 12:19

1 Answers1

3

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563