2

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?

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

Let me know if it is clear.

Sign up to request clarification or add additional context in comments.

1 Comment

wouldn't the use of trim nicer instead of str_replace to clean up the words?
2

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

2 Comments

If list of allowed or filtered words will get bigger, this will use a lot of CPU. We should always think of such cases, even while learning.
@Megakuh that's interesting. Are you poiting on the use of the pReg library or is there some other heavy CPU thing in here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.