php preg_replace两个或多个空格


php preg_replace two or more spaces

我希望替换多个空格字符实例。我最初的搜索似乎都集中在使用/s上,但这包括换行符和其他空白

我认为这应该很接近?用一个空间替换两个或多个实例空间" "

preg_replace('/ {2,}/', ' ', $string);

试试这个怎么样:

preg_replace('/'s's+/', ' ', $string);
$str = <<<EOT
word  word   123.
new line  word

new line  word
EOT;
$replaced = preg_replace('#'h{2,}#', ' ', $str);
var_dump($replaced);

输出:

word word 123.
new line word

new line word

'h匹配任何水平空白字符(相当于[[:blank:]]
{2,}2之间匹配前一个令牌,次数不限次,尽可能多次,根据需要反馈(贪婪)

学分:https://regex101.com/

使用'v表示垂直空白,使用's表示任何空白。