note 90503 added to function.preg-match
| From: | corey | Date: | Sat, 25 Apr 2009 03:52:27 +0000 |
| Subject: | note 90503 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-153707@lists.php.net to get a copy of this message | ||
I see a lot of people trying to put together phone regex's and struggling (hey, no
worries...they're complicated). Here's one that we use that's pretty nifty. It's
not perfect, but it should work for most non-idealists.
*** Note: Only matches U.S. phone numbers. ***
<?
// all on one line...
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))?
?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';
// or broken up
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})'
.'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})'
.'[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';
?>
If you're wondering why all the non-capturing subpatterns (which look like this
"(?:", it's so that we can do this:
<?
$formatted = preg_replace($regex, '($1) $2-$3 ext. $4', $phoneNumber);
// or, provided you use the $matches argument in preg_match
$formatted = "($matches[1]) $matches[2]-$matches[3]";
if ($matches[4]) $formatted .= " $matches[4]";
?>
*** Results: ***
520-555-5542 :: MATCH
520.555.5542 :: MATCH
5205555542 :: MATCH
520 555 5542 :: MATCH
520) 555-5542 :: FAIL
(520 555-5542 :: FAIL
(520)555-5542 :: MATCH
(520) 555-5542 :: MATCH
(520) 555 5542 :: MATCH
520-555.5542 :: MATCH
520 555-0555 :: MATCH
(520)5555542 :: MATCH
520.555-4523 :: MATCH
19991114444 :: FAIL
19995554444 :: MATCH
514 555 1231 :: MATCH
1 555 555 5555 :: MATCH
1.555.555.5555 :: MATCH
1-555-555-5555 :: MATCH
520-555-5542 ext.123 :: MATCH
520.555.5542 EXT 123 :: MATCH
5205555542 Ext. 7712 :: MATCH
520 555 5542 ext 5 :: MATCH
520) 555-5542 :: FAIL
(520 555-5542 :: FAIL
(520)555-5542 ext .4 :: FAIL
(512) 555-1234 ext. 123 :: MATCH
1(555)555-5555 :: MATCH
----
Server IP: 208.69.120.35
Probable Submitter: 72.177.49.202
----
Manual Page -- http://www.php.net/manual/en/function.preg-match.php
Edit -- https://master.php.net/note/edit/90503
Del: integrated -- https://master.php.net/note/delete/90503/integrated
Del: useless -- https://master.php.net/note/delete/90503/useless
Del: bad code -- https://master.php.net/note/delete/90503/bad+code
Del: spam -- https://master.php.net/note/delete/90503/spam
Del: non-english -- https://master.php.net/note/delete/90503/non-english
Del: in docs -- https://master.php.net/note/delete/90503/in+docs
Del: other reasons-- https://master.php.net/note/delete/90503
Reject -- https://master.php.net/note/reject/90503
Search -- https://master.php.net/manage/user-notes.php