2

我有一个字符串:

$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

4

2 回答 2

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 );

让我知道是否清楚。

于 2013-02-26T11:54:29.337 回答
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);
于 2013-02-26T12:01:22.910 回答