skip to Main Content

I have a string in php

$string = "a very long text ...."

I would like to check if this string contains any of the following words

$forbidden_words = array("word1", "word2", "word3");

I know I can use

if (str_contains('abc', '')) { .... }

but this works for only one word. How can I select the string if does not contain any of the words in the array ?

3

Answers


  1. You can use a loop to iterate over the array of forbidden words and check if any of them exist:

    $string = "a very long text ....";
    $forbidden_words = array("word1", "word2", "word3");
    
    foreach ($forbidden_words as $word) {
        if (str_contains($string, $word)) {
            echo "The string contains the word: $word";
        }
    }
    

    Alternative to check if any of them appear in the string (using strpos) :

    $string = "a very long text ....";
    $forbidden_words = array("word1", "word2", "word3");
    $contains_forbidden_word = false;
    
    foreach ($forbidden_words as $word) {
        if (strpos($string, $word) !== false) {
            $contains_forbidden_word = true;
            break;
        }
    }
    
    if (!$contains_forbidden_word) {
        // The string does not contain any of the forbidden words
    }
    
    Login or Signup to reply.
  2. You can use a regex to check for all the words in one run.

    $forbidden_words = array("word1", "word2", "word3");
    $string = "a very long text ....";
    if(preg_match('/b(' . implode('|', array_map('preg_quote', $forbidden_words)) .  ')b/')) {
        echo 'have forbidden word(s)';
    }
    

    This uses word boundaries to ensure partial word matches don’t match. In demo below word1 won’t match word, vice versa would occur with string functions (e.g. strpos). An i modifier can be added after closing delimiter if this should be case insensitive.

    https://3v4l.org/Y4gTJ

    Login or Signup to reply.
  3. You could form a regex alternation of the blacklisted keywords and then use preg_match():

    $string = "a very long text ....";
    $forbidden_words = array("word1", "word2", "word3");
    $regex = "/b(?:" . implode("|", $forbidden_words) . ")b/";
    if (!preg_match($regex, $string)) {
        echo "MATCH";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search