简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM