2013-02-17 190 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