带有短划线和数字的PHP preg_replace电话号码

时间:2015-04-08 10:37:04

标签: php preg-replace

我的数据库中列出了几种以某种写作方式出现的电话号码 我想在每两个数字之后有一个空格。我以为我会这样做:

$numbers = '06-12345678';
$regex = '/(\\d{2})(\\d{1})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/';
$result = preg_replace($regex, '$1 $2 $3 $4 $5 $6', $numbers);
echo $result;

但这不起作用。它只是将所有数字放在一起。

我的预期输出:

06 - 12 34 56 78

1 个答案:

答案 0 :(得分:2)

这应该适合你:

$numbers = "06-12345678";
echo $result = preg_replace("/(\d{2})-(\d{2})(\d{2})(\d{2})(\d{2})/", "$1 - $2 $3 $4 $5", $numbers);

正则表达式解释:

(\d{2})-(\d{2})(\d{2})(\d{2})(\d{2})
  • 第一个捕获组(\ d {2})
  • \ d {2} 匹配数字[0-9]
    • 量词: {2} 正好2次
  • - 匹配字符 - 字面意思
  • 第二个捕获组(\ d {2})//< - 4x相同
  • \ d {2} 匹配数字[0-9]
    • 量词: {2} 正好2次

输出:

06 - 12 34 56 78