Phone and Email REGEX for PHP
I, and a few other developers I work with, looked the Internet over for a good REGEX that will pull a valid phone number from HTML content. The challenge is the many different ways a phone number can be formated. (ie. 123-456-7890, 123.456.7890, 1(123)456-7890, etc.)
We got together and spent an hour and created the following bit of code. It will capture the phone and email regardless of the phone formatting.
<?
$site = ‘http://www.somedomain.com/’;
$c = curl_init();
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($c, CURLOPT_URL, $site);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_POST, 0);
$return = curl_exec($c);
# Phone Numbers
if(preg_match_all(
“/(?<!\/)(?<![0-9]{1})[(]{0,1}([2-9]{1}[0-9]{2})[)-.]{0,1}[ ]{0,1}”.
“(?<!\/)(?<=(?<=[2-9]{1}[0-9]{2})|[ ]|[-]|[.]|[)])
[ ]{0,1}([2-9]{1}[0-9]{2})[-. ]{0,1}”.
“[]?[0-9]{4}[ ]{0,1}(?![0-9]{1})”.
“((x|ext)[.]{0,1}[ ]{0,1}([0-9]{1,7}))?/”,$return,$phones)
)
{
echo ‘Got it!<br>’;
echo ‘<pre>’;
print_r($phones[0]);
echo ‘</pre>’;
}
# Any Email
if(preg_match_all(“/[^\s()<>\[\]{}@,.]{1}[^\s()<>\[\]{}@,]*
@[^\s()<>\[\]{}@,.]{1}[^\s()<>\[\]{}@,]*[.]{1}[a-z0-9]{2,4}/i”,$return,$email))
{
echo ‘Got it!<br>’;
echo ‘<pre>’;
print_r($email);
echo ‘</pre>’;
}
curl_close($c);
?>









>
Follow Me (digitally you stalker)