A regular expression to extract a business extension from a phone number
I am having the dang-est time trying to write a regex that will extract the phone extension from a full phone number string. This should work on a number like this one: 777.777.7777 x 7302
It should also work using "ext", "EXT", "Ext", "eXt", "ext.", a开发者_Go百科nd "Ext ". Essentially just cover all the common ground use of it.
I just need the "x 7302" part. In fact I am just going to strip it down to just the extension number once I extract it.
Can anyone help me please? Regular expressions are something that I struggle with when they get more complex.
I am doing this in a PHP function (preg_match) if that will help anyone.
This probably helps to give you something to play with:
$phonenumber = '777.777.7777 x 7302';
$extension = preg_replace('(^.*(ext|x) ?([0-9]+)$)i', '$2', $phonenumber);
echo $extension;
Use the i
modifier (at the end) to make the regex case insensitive so to match all combinations of ext
. I used a group to offer both variant: ext
or x
: (ext|x)
.
The rest is looking for a number at the end, and a space is possible between EXT and the number.
try with regex:
/e?xt?\.?\s*\d+$/i
<?
echo "<pre>";
$phone = '777.777.7777 x 7302';
preg_match("/e?xt?\.?\s*\d+$/i", $phone, $matched);
print_r($matched);
?>
Output:
Array
(
[0] => x 7302
)
\w+\s*\d+$
It is an simpler regex assuming that the input is similar to what you have provided.
This should do it for you
/([\d\-\.]+)([ext\. ]+)(\d+)/i
The first set matches the numbers separated by dash or dot. The second set matches your extension string and the third set matches your extension number.
If you just want the last numbers of the string, you can use:
\D+(\d+)$
\D+
at least one non-digit followed by:
(\d+)
at least one digit (captured using parenthesis)
$
at the end of the string.
I am a bit leery of regular expression, so I'm a bit biased when I say, is it possible to just split the string using the PHP function "explode()", using the 'x' character as your delimiter?
Here is a link to the PHP manual for that function if you are not familiar with it:
Explode()
Try this function:
$pn = "777.777.7777 x 7302";
function get_ext($pn)
{
$ext = preg_replace('/[\d\.\s]+[ext\s]+(\d{1,})/i', '$1', $pn);
return $ext;
}
echo get_ext($pn);
//7302
精彩评论