2011-12-20 105 views
3

如何打开$string用PHP删除多余的空格?

"one two    three" 

到:

"one two three" 

+0

复制的[preg_replace函数非α,离开单一的空白字符(http://stackoverflow.com/questions/8329065/preg-replace-non-alpha-leave-single- whitespaces) – 2011-12-20 05:57:44

回答

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

这将用一个空格替换一个或多个空格。它也将用自己替换一个空间!为了改善它:

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

它用一个空格替换一组2个或更多连续空格。

+1

我想'preg_replace('/ s + /','',$ str);'会好一点。 – 2011-12-20 06:02:16

0

尝试:

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