2011-12-20 92 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);