Adam
Adam

Reputation: 20872

PHP String - Remove Array or Words & Check for Others

I have a String:

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

I also have 2 std arrays as follows that contain a number of words:

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

eg:

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

How can I take the string $data and first remove any words from the $profanityTextAllowedArray and then check the string $data for any words in the $profanityTextNotAllowedArray which should be flagged?

Upvotes: 2

Views: 179

Answers (2)

Wouter J
Wouter J

Reputation: 41934

Something like this can help you:

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

Upvotes: 2

Serge Kuharev
Serge Kuharev

Reputation: 1052

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

Let me know if it is clear.

Upvotes: 3

Related Questions