Check for an array of words in a string in php

Discuss coding issues, and scripts related to PHP and MySQL.
Marius
Posts: 97

Check for an array of words in a string in php

I have a list of spam words that are into an array. When a user submits a string text, I want to know if it contains these words. How can I do this efficiently?
I wrote this code:

Code: Select all

$my_words = 'buy;sell;shop;purchase';
$array_words = explode(';' ,$my_words); //convert the list to an array
$input_text = 'we can sell your products'; //user will input this text

foreach($array_words as $word){
  if(strpos($input_text  ,$word) !== false)   return 'You can't use from this text';
}
But if I have many special words in the array, the foreach() slows down the execution speed.

Admin
You could add the spam words into a string, with | as word separator and then use regular expression to check.

Code: Select all

$my_words = 'buy|sell|shop|purchase';

$input_text = 'we can sell your products'; //user will input this text

if(preg_match('#\b(?:'.$my_words.')\b#i', $input_text, $mt)) echo 'Match: '.$mt[0];
else echo 'No match';
Here is an explanation of the (exact) regex built and used above:

Code: Select all

/\b(?:buy|sell|shop|purchase)\b/i

\b    match the start of a word, which is either
(?:
  buy
  |    OR
  sell
  |    OR
  shop
  |    OR
  purchase
)
\b    match the end of a word
i    flag to disable case sensitivity

Similar Topics