Reputation: 490
I am having a plain text which contains phone numbers in different patterns. I need to find phone number pattern exists in the plain text. I have done this
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';
$text = "fhsd hjkh ksd fsd fjkfhdsk 333-445-33333 sdfhjksdh s sdfjksd fdf";
if(preg_match($regex,$text,$match)){
print_r($match);
}else echo "not found";
It detects the phone number only if we give the phone number as input. It is not detecting the phone number pattern in the plain text.
Please help me in this. Thanks in advance!
Upvotes: 0
Views: 1019
Reputation: 1
use this expression for hyphen separated phone no.
$regex = '/\d+-\d+-\d+/';
Upvotes: 0
Reputation: 4021
Remove ^
from the beginning and $
from the end of the regular expression:
$regex = '/(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?/';
You may read more about anchors.
UPDATE: The regular expression for a hyphen-separated phone number in three parts should be this:
$regex = '/\\d+-\\d+-\\d+/';
Upvotes: 3