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?

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.