2

如何在 3 位和 4 位数字后添加空格?

我有这个号码:+4420719480

结果需要是:+44 2071 9480

如何在 4 个字符后添加带有 css 或 php 的空格?

我尝试了以下代码:

$str = "+4420719480";
echo chunk_split($str, 4, ' ');

但是如何将空格添加到前 3 个字符,然后添加到第 4 个字符?

4

3 回答 3

3

您可以使用 preg_replace

$str = '+4420719480';
echo preg_replace('~^.{3}|.{4}(?!$)~', '$0 ', $str);

图案解释:

~           # pattern delimiter
^.{3}       # any character 3 times at the start of the string
|           # OR
.{4}        # any character 4 times
(?!$)       # not followed by the end of the string
~           # pattern delimiter

替换:('$0 ' 整个图案和一个空格)

于 2013-08-24T20:44:50.230 回答
1

有时,最普通的解决方案也能很好地完成这项工作。

$str = "+4420719480";
$new = substr($str,0,3).' '.substr($str,3,4).' '.substr($str,7);
于 2013-08-24T21:02:16.113 回答
0

使用您的代码,您可以执行以下操作:

$str = "+4420719480";
echo strrev(chunk_split(strrev($str),4," "));

有点笨重,只适用于这种尺寸$str,但它有效!

于 2013-08-24T20:52:27.040 回答