2013-02-17 189 views
2

刪除一些話我有這樣的字符串:解析字符串 - 從字符串

$text = 'Hello this is my string and texts'; 

我有一些不允許在陣列話:

$filtered_words = array(
      'string', 
      'text' 
     ); 

我要全部更換我在$text***過濾詞,所以我寫道:

$text_array = explode(' ', $text); 
     foreach($text_array as $key => $value){ 
      if(in_array($text_array[$key], $filtered_words)){ 
       $text = str_replace($text_array[$key], '***', $text); 
      } 
     } 
echo $text; 

輸出:

Hello this is my *** and texts 

但我需要的功能也與***取代texts,因爲它也包含過濾詞(文本)。

我怎麼能做到這一點?

由於

+0

http://php.net/str_replace - 搜索*數組*,它的工作原理。替換字符串是'***' - 只需檢查手動PHP是否開箱即用 - 請參閱[答案](http://stackoverflow.com/a/14919021/367456) – hakre 2013-02-17 07:43:13

回答

10

你可以做它了,str_replace支持從陣列替換成一個字符串:

$text = 'Hello this is my string and texts'; 

$filtered_words = array(
    'string', 
    'texts', 
    'text', 
); 

$zap = '***'; 

$filtered_text = str_replace($filtered_words, $zap, $text); 

echo $filtered_text; 

輸出(Demo):

Hello this is my *** and *** 

小心你有最大的話先記住,當str_replace是在這種模式下,它會做一個替換後,其他r - 就像你的循環中一樣。如果較早的話,較短的單詞可能是較大單詞的一部分。

如果您需要更多失敗保護,您必須首先考慮進行文本分析。這也可以告訴你,如果你不知道你可能想要替換的話,但是你到目前爲止還沒有想到。

+1

+1瞭解詳情。你的回答比我的完整。 – dfsq 2013-02-17 07:54:54

+0

從$ filter_words中排除單詞'text',那麼輸出將是'你好,這是我的***和*** s',但是這應該是'你好,這是我的***和***' – behz4d 2013-02-17 08:19:08

+0

謝謝你真是太棒了! – rdllngr 2016-08-28 23:19:36

2

str_replace可以接受的陣列作爲第一個參數。所以沒必要任何for each循環可言的:

$filtered_words = array(
    'string', 
    'text' 
); 
$text = str_replace($filtered_words, '***', $text); 
+0

短而甜! – behz4d 2013-02-17 07:48:08