2012-02-22 21 views
25

我希望能夠用-替換空格,但也希望刪除逗號和問號。我怎樣才能在一個功能中做到這一點?如何從PHP中的文本字符串替換多個項目?

到目前爲止,我把它替換空格:

str_replace(" ","-",$title) 
+2

[您可以將多個搜索值傳遞給'str_replace()'](http://php.net/manual/en/function.str-replace.php)。 – JJJ 2012-02-22 11:29:30

回答

128

您可以將數組作爲參數傳遞給str_replace()。檢查manual

// Provides: You should eat pizza, beer, and ice cream every day 
$phrase = "You should eat fruits, vegetables, and fiber every day."; 
$healthy = ["fruits", "vegetables", "fiber"]; 
$yummy = ["pizza", "beer", "ice cream"]; 

$newPhrase = str_replace($healthy, $yummy, $phrase); 
+27

最好。示例代碼。永遠。 – 2012-02-22 11:30:53

+13

不是我的。這是來自PHP手冊;) – Napolux 2012-02-22 11:31:30

+3

@Napolux然後鏈接手冊頁。 :) – 2012-02-22 11:41:07