繁体   English   中英

使用PHP格式化电话区号

[英]Format Phone Area Code with PHP

我们网站上有很多办公地点,每个办公地点都有一个主要电话号码-输入的许多电话都带有以下区号: (800) 555-5555

无论输入的内容如何,​​这都是我需要他们看上去的方式: 800- 555-5555

这是我现在的位置

str_replace(array( '(', ')' ), '', $this->data['location_phone']);

虽然这删除了两个括号,但我实际上只需要删除开头的括号,并用破折号替换结尾的括号。

使用阵列进行替换。

str_replace(array( '(', ')' ), array('', '-'), $this->data['location_phone']);

您可以在str_replace文档页面上阅读更多内容。

您可以执行与已经执行的操作类似的操作。代替将()替换为'' ,可以仅使用-替换(然后替换)

str_replace(array('('), '', $this->data['location_phone']);

str_replace(array(')'), '-', $this->data['location_phone']);

甚至更好,合并为一行(如其他答案所示):

str_replace(array( '(', ')' ), array('', '-'), $this->data['location_phone']);

这个答案似乎可以解决preg_match和数据重建问题。 但是在该答案中发布的正则表达式对于此处描述的数据清理不是那么好。

因此,请尝试将这个答案的变体放在一起,它使用了来自官方PHP文档中某个帖子的一些出色的正则表达式:

// Set test data.
$test_data = array();
$test_data[] = '1 800 555-5555';
$test_data[] = '1-800-555-5555';
$test_data[] = '800-555-5555';
$test_data[] = '(800) 555-5555';

// Set the regex.
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';

// Roll through the test data & process.
foreach ($test_data as $data) {
  if (preg_match($regex, $data, $matches)) {

    // Reconstruct the number based on the captured data.
    echo "New number is: " . $matches[1] . '-' . $matches[2] . '-' . $matches[3] . '<br />';

    // Dump the matches to check what is being captured.
    echo '<pre>';
    print_r($matches);
    echo '</pre>';

  }
}

清洗后的结果(包括preg_match匹配项)将为:

New number is: 800-555-5555
Array
(
    [0] => 1 800 555-5555
    [1] => 800
    [2] => 555
    [3] => 5555
)
New number is: 800-555-5555
Array
(
    [0] => 1-800-555-5555
    [1] => 800
    [2] => 555
    [3] => 5555
)
New number is: 800-555-5555
Array
(
    [0] => 800-555-5555
    [1] => 800
    [2] => 555
    [3] => 5555
)
New number is: 800-555-5555
Array
(
    [0] => (800) 555-5555
    [1] => 800
    [2] => 555
    [3] => 5555
)

谢谢。 我用它作为电话号码以去除所有空格和(),以及-所以tel:// 1234567890

href = tel://“。str_replace(array('(',')','','-'),array('','','',''),$ row [” ContactPhone“] )。“>”。$ row [“ ContactPhone”]。“

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM