I am using preg_match to extract the various sections of a US-based phone number from within a paragraph of text. I can already extract the number. But I want to make match[0] include only the phone numbers.
Problem: My pattern comes close, but I need some help to get rid of whatever text is before the phone number. How do I get rid of the preceding string "Hey my phone is "?
PHP Code
$pattern = '/.*?(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})'
.'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})'
.'[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?.*?/';;
$subject = 'Hey my phone is 911-628-4539, call me tonight at 9:16:00pm, my room is 122-1001';
preg_match($pattern, $subject, $match);
print_r($match);
Output
Array ( [0] => Hey my phone is 911-628-4539 [1] => 911 [2] => 628 [3] => 4539 )
Just remove :
.*?from your regex. If you don’t need it why match it?