Format phone number

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
aj120
Forum Newbie
Posts: 2
Joined: Sun Nov 30, 2008 5:49 pm

Format phone number

Post by aj120 »

~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


New to Php/Regex code -trying to format a 10 digit phone number with input:
123456
expected result: 123-456-789
various attempts -trying to learn look behind /look ahead - not working (with error messages shown)
code shown below
thanks for your help

Code: Select all

<?php
 
$phoneno = "1234567890";
 
 
$pattern="/(?<=(\d\d\d))(?=(\d\d\d\d)+$)/";  
//output:  123456-7890
 
 
//$pattern="/(?<=(\d\d\d+)(?=(\d\d\d\d)+$)/";  
//Warning: preg_replace() [function.preg-replace]: Compilation failed: missing ) at offset 29 in C:\wamp\www\regex\phone-no.php on line 18
 
//$pattern="/(?<=(\d\d\d)(\d\d\d)(?=(\d\d\d\d)+$)/";  
//Warning: preg_replace() [function.preg-replace]: Compilation failed: missing ) at offset 36 in C:\wamp\www\regex\phone-no.php on line 11 
 
 
$replacement = "-";
 
echo preg_replace($pattern, $replacement, $phoneno);
 
//expected result:  123-456-7890
 
?>

~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: Format phone number

Post by Kieran Huggins »

There are a couple of good regexen here: http://regexlib.com/DisplayPatterns.asp ... tegoryId=7

Might be useful as examples!
mintedjo
Forum Contributor
Posts: 153
Joined: Wed Nov 19, 2008 6:23 am

Re: Format phone number

Post by mintedjo »

Code: Select all

preg_replace("/(\d{3})(\d{3})(\d{4})/m", "$1-$2-$3", $phoneNumber)
?

Using lookahead and lookbehind for this didnt seem to work too well :-(
aj120
Forum Newbie
Posts: 2
Joined: Sun Nov 30, 2008 5:49 pm

Re: Format phone number

Post by aj120 »

Thanks all for your help!
Solution worked great
Regexn ref was also very useful.
Sorry for delaying in replying
Post Reply