How do you format a 10 digit string into a phone number?

爱⌒轻易说出口 提交于 2019-11-28 06:54:50
SoapBox

A regex is definitely overkill for this one. If you wanted to take a "phone number" and normalize it to 10 digits, that would be a good use for a regex. To do what you're asking, just do something like:

echo '('.substr($data, 0, 3).') '.substr($data, 3, 3).'-'.substr($data,6);

Since you already know how to divide up your data, you can just use substr or something similar to grab the parts you want. RegEx is useful for matching strings which don't always have a strict format. (Like variable numbers of spaces, variable stuff before or after it, extra dashes, etc). But in your case the input is always strictly formatted 10 digits, nothing else, so you don't need the extra overhead of a RegEx to format it.

Rubens Farias

Take a look here: Format phone number

function format_phone($phone)
{
    $phone = preg_replace("/^\d/", "", $phone);

    if(strlen($phone) == 7)
        return preg_replace("/(\d{3})(\d{4})/", "$1-$2", $phone);
    elseif(strlen($phone) == 10)
        return preg_replace("/(\d{3})(\d{3})(\d{4})/", "($1) $2-$3", $phone);
    else
        return $phone;
}

I'd probably go with

$num = "4085551234";  // given                                                  
$formatted = "(".substr($num,0,3).") ".substr($num,3,3)."-".substr($num,6);

Regex isn't really appropriate here.

Trivially you could do something like:

\(\d\{3\}\)\(\d\{3\}\)\(\d\{4\}\)

To match the 10 digits into 3 subgroup expressions, and then print them out using each subgroup:

"(\1) \2-\3

But in practice free form data is usually a little trickier

I had to do this question for my advanced placement computer science class. Java:

Write a program that accepts a 10 digit # and formats it as a phone number.

Ex: 705726552
Output: (705)726-2552

import java.util.Scanner;
  public class  TelNumCorrection{

  public static void main(String[]args){

    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a 10 digit number");
    String num=scan.nextLine();

    String a=num.substring(0,3);
    String b=num.substring(3,6);
    String c=num.substring(6);
    System.out.println("("+a+ ")"+b+"-"+c);
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!