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


PHP preg_replace phonenumber with dash and numbers

我的数据库中列出了几个电话号码,它们都是用某种书写方式编写的
我想在每两个数字后面留一个空格。我想我会做:

$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

这应该适用于您:

$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})//<-4倍相同
  • ''d{2}匹配数字[0-9]
    • 量词:{2}正好2次

输出:

06 - 12 34 56 78