如果连字符在数字之间,请删除空格

时间:2018-07-16 12:52:22

标签: php regex

我有以下字符串:

$string = '66 hello 2.3 - 44 world 99 -8';

我需要一个正则表达式来删除字符-之间的空格,如果它用数字包裹着。因此,在上面的示例中,我们最终得到:

$string = '66 hello 2.3-44 world 99-8';

什么是合适的正则表达式方法?

3 个答案:

答案 0 :(得分:2)

这是您的方法:

$string = '66 hello 2.3 - 44 world 99 -8';

$string_without_spaces = preg_replace('(\d)\s*(\-)\s*(\d)', '\1\2\3', $string);

https://regex101.com/r/jYIyYz/3

答案 1 :(得分:0)

这是我对此的解决方案:

$string = '66 hello 2.3 - 44 world 99 -8';

echo preg_replace('[-\s(?=\d)]', '-', preg_replace('[(?<=\d)\s-]', '-', $string));

仅当在前面或后面找到数字时,才替换连字符。

答案 2 :(得分:-1)

在任何情况下,如果您的横排空格两侧都没有数字?如果没有,只需使用str_replace()

用破折号代替空格
<?php

$string = '66 hello 2.3 - 44 world 99 -8';
$string = str_replace(' - ', '-', $string);
echo $string; //66 hello 2.3-44 world 99 -8

http://php.net/manual/en/function.str-replace.php

如果确实如此,请使用正则表达式。符合条件:

#\d\s-\s\d#

使用此代码:

$regex = '#\d\s-\s\d#';
$string = '66 hello 2.3 - 44 world 99 -8 another dash - but no numbers';
echo preg_replace($regex, '-', $string);

将输出:

66 hello 2.-4 world 99 -8 another dash - but no numbers

您可以在这里看到

https://3v4l.org/Fesve

如果您想摆弄正则表达式,这里是:

https://regex101.com/r/a7l2dW/1

相关问题