Welcome Guest, Not a member yet? Register   Sign In
Formatting Number with Regular Expression
#1

[eluser]tkaw220[/eluser]
Hi,

I would like to add a "dash" after every 3 digits in a given numbers (10 digits). For example, 9785678941 became 978-567-894-1. How could I achieve this with regular expression by using PHP preg_replace?

Thank you.
#2

[eluser]pickupman[/eluser]
Try this:
Code:
$phone_str ='1234567890';
$result = preg_replace('/\(?\b([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{3})[-. ]?([0-9]{1})\b/si', '$1-$2-$3-$4', $phone_str);

var_dump($result);
#3

[eluser]tkaw220[/eluser]
Hello pickupman,

Your regex is not working for me. But I do get a working code from Dreamweaver forum:

$result = preg_replace('/(\\d{3})(\\d{3})(\\d{3})(\\d{1})/', '${1}-${2}-${3}-${4}', $phone_str);

However, this regex applied to string with exact length (ie., 10 digits in this case) but break if the string has different length, ie., 14 digits. Any idea on how to modify it so that it always add a dash after every 3 digits at any string length?

Thank you very much and have a nice day.

Best regards,
Edwin
#4

[eluser]pickupman[/eluser]
Ah...you asked for 10 digit strings first time. I am not a regex wiz but a while loop may work easier as it would work for any length of string
Code:
$input = '1234567111890';
$output = '';

while(strlen($input) > 0){
    $output .= substr($input, 0, 3) . '-'; #take first 3 digits
    $input = substr($input, 3); #remove those 3 digits from string
}
$output = rtrim($output, '-'); #remove trailing -
var_dump($output);
unset($input); #tidy up

You may want to test if $input is numeric if you didn't want any alpha characters.
#5

[eluser]tkaw220[/eluser]
Dear pickupman,

Yes, your code works perfectly. Huge thank to you.

Have a nice weekend.

Best regards,
Edwin




Theme © iAndrew 2016 - Forum software by © MyBB