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!
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+/';
use this expression for hyphen separated phone no.
$regex = '/\\d+-\\d+-\\d+/';
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.