PHP从字符串中删除空格,但仅从数字之间删除空格

时间:2019-10-12 10:34:40

标签: php regex string

我的输入是

07786 000 000 Marie Claire

我想要的输出是

07786000000 Marie Claire

基本上,我只想删除数字之间的空格。

到目前为止,我的尝试删除了所有空格

$phone_number = preg_replace('/\s+/', '', $phone_number);

2 个答案:

答案 0 :(得分:4)

使用环视

(?<=\d)\s+(?=\d)

请参见a demo on regex101.com


PHP中:

$regex = "~(?<=\d)\s+(?=\d)~";
$phone_number = preg_replace($regex, '', $phone_number);

答案 1 :(得分:2)

以下是使用preg_replace的选项:

$input = "07786 000 000 Marie Claire";
$output = preg_replace("/(\d)\s+(\d)/", "$1$2", $input);
echo $input . "\n" . $output;

此打印:

07786 000 000 Marie Claire
07786000000 Marie Claire