PHP字符串 - 删除数组或单词&检查其他人

时间:2013-02-26 11:47:32

标签: php arrays string match

我有一个字符串:

$data = "String contains works like apples, peaches, banana, bananashake, appletart";

我还有2个std数组,包含许多单词:

$profanityTextAllowedArray = array();
$profanityTextNotAllowedArray = array();

例如:

$profanityTextAllowedArray
(
    [0] => apples
    [1] => kiwi
    [2] => mango
    [3] => pineapple
)

如何获取字符串$data并首先删除$profanityTextAllowedArray中的任何字词,然后检查字符串$data以查找$profanityTextNotAllowedArray中应标记的任何字词?

2 个答案:

答案 0 :(得分:3)

$list = explode( ' ', $data );

foreach( $list as $key => $word ) {
  $cleanWord = str_replace( array(','), '', $word ); // Clean word from commas, etc.
  if( !in_array( $cleanWord, $profanityTextAllowedArray ) ) {
    unset($list[$key]);
  }
}

$newData = implode( ' ', $list );

如果清楚的话,请告诉我。

答案 1 :(得分:2)

这样的事情可以帮到你:

$data = "apples, peaches, banana, bananashake, appletart";

$allowedWords = array('apples', 'peaches', 'banana');
$notAllowedWords = array('foo', 'appletart', 'bananashake');

$allowedWordsFilteredString = preg_replace('/\b('.implode('|', $allowedWords).')\b/', '', $data);

$wordsThatNeedsToBeFlagged = array_filter($notAllowedWords, function ($word) use ($allowedWordsFilteredString) {
    return false !== strpos($allowedWordsFilteredString, $word);
});

var_dump($wordsThatNeedsToBeFlagged);