2011-07-20 22 views
3

我想要去除那些不是兩個字母之間所有空格:條在一個PHP字符串中的所有不必要的空格

$string = "    bah bah bah bah "; 
$string = str_replace("/w /w", "+", $string); 
// what goes here? to get this: 
$string = "bah+bah+bah+bah"; 

的想法是,我想擺脫所有不必要的空格(不僅在開始和結束)。這不是一個鏈接,但對於一個搜索框,上提交將被分解,因此+甚至是=什麼的基本上

回答

7
$string = preg_replace('/\s+/', ' ', $string); 
+0

和$ string = trim($ string)將所有步驟縮合爲一個。好吧,我會接受它 – faq

+0

是的,你也可以直接把它放在'preg_replace()' – casraf

+0

爲什麼這個字符類? –

3

如果你的最終目標是爆炸搜索字符串(即到我建議使用preg_split()

$search_terms = preg_split('/\s+/', $search_string); 
print_r($search_terms); 
+0

爲什麼要上角色課? –

+0

原因我複製並粘貼:)。請參閱編輯。 –

+0

Tsk tsk抄襲! –

相關問題