2013-06-20 24 views
0

我試圖替換+的所有空間的字符串,但我做的preg_replace()之後,我得到一個空字符串作爲結果。試圖替換+所有空格字符串

爲什麼?我究竟做錯了什麼?

$query = "hello world"; 
$formattedQuery = preg_replace('\s', '+', $query); 
echo "formatted Query is: ".$formattedQuery; 
/* output should be hello+world, but I am getting nothing/blank string outputted */ 
+1

你可以只使用'$ formattedQuery = str_replace函數(」」, '+',$查詢);' – Karl

回答

7

爲什麼不使用str_replace()

$query = "hello world"; 
$formattedQuery = str_replace(' ', '+', $query); 
echo "formatted Query is: ".$formattedQuery; 

如果您堅持使用preg_replace()然後打開第一個參數爲正則表達式:

$query = "hello world"; 
$formattedQuery = preg_replace('/\s+/', '+', $query); 
echo "formatted Query is: ".$formattedQuery; 
+5

良好的通話 - 簡單的情況 「其中y替換x」,不要在正則表達式廢品處理。真正的模式匹配調用正則表達式函數。 str_replace()在這裏是正確的解決方案。 –

+0

這就是我的感受 –

+0

這是一條評論 – xtechkid

1

對了preg_replace,嘗試:

preg_replace('/\s+/', '+', $query); 
4

如果您使用過的URL數據你真正需要的是工作urlencode不能代替空格

$query = "hello world"; 
echo urlencode($query); 

如果沒有,那麼你可以使用

echo preg_replace('/\s+/', "+", $query); 

輸出

hello+world 
1

$ formattedQuery = preg_replace('/ \ s /','+',$ query);