Page 1 of 1

Format phone number

Posted: Sun Nov 30, 2008 5:58 pm
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.

Re: Format phone number

Posted: Sun Nov 30, 2008 6:35 pm
by Kieran Huggins
There are a couple of good regexen here: http://regexlib.com/DisplayPatterns.asp ... tegoryId=7

Might be useful as examples!

Re: Format phone number

Posted: Mon Dec 01, 2008 4:09 am
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 :-(

Re: Format phone number

Posted: Mon Dec 01, 2008 5:25 pm
by aj120
Thanks all for your help!
Solution worked great
Regexn ref was also very useful.
Sorry for delaying in replying