Learner231
Learner231

Reputation: 35

Check for an array of words in a string in php

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

$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, the foreach slows down the execution speed.

Upvotes: 1

Views: 69

Answers (2)

Wakeel
Wakeel

Reputation: 5002

You could use | as word separator and then use regular expression to check

$my_words = 'buy|sell|shop|purchase';
$input_text = 'we can sell your products'; //user will input this text
return preg_match('#(?:'.$my_words.')#i', $input_text);

Use i flag to disable case sensitivity

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521239

You may form a regex alternation based on your semicolon-delimited string, and then search for that:

$my_words = 'buy;sell;shop;purchase';
$regex = '/\b(?:' . str_replace(";", "|", $my_words) . ")\b/";
$input_text = 'we can sell your products';
if (preg_match($regex, $input_text)) {
    echo "MATCH";
}
else {
    echo "NO MATCH";
}

Here is an explanation of the (exact) regex built and used above:

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

\b            match the start of a word, which is either
(?:
    buy
    |         OR
    sell
    |         OR
    shop
    |         OR
    purchase
)
\b            match the end of a word

Upvotes: 3

Related Questions