使用PHP删除多余的空格?

3

我该如何将$string进行转换:

"one    two              three"

into:

"one two three"

?


2个回答

3
$str = "one    two              three";
$str = preg_replace('/ +/',' ',$str);

这个函数将一个或多个空格替换为一个空格。它也会将单个空格替换为它本身!! 为了使其更好:

$str = preg_replace('/ {2,}/',' ',$str);

该函数用单个空格替换一组2个或更多连续的空格。


1
我认为preg_replace('/s+/',' ',$str);会更好一些。 - Jesse Good

0

试试这个:

$str = preg_replace("/[ ]{2,}/", " ", $str);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接