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
You can use a loop to iterate over the array of forbidden words and check if any of them exist:
Alternative to check if any of them appear in the string (using
strpos
) :You can use a regex to check for all the words in one run.
This uses word boundaries to ensure partial word matches don’t match. In demo below
word1
won’t matchword
, vice versa would occur with string functions (e.g.strpos
). Ani
modifier can be added after closing delimiter if this should be case insensitive.https://3v4l.org/Y4gTJ
You could form a regex alternation of the blacklisted keywords and then use
preg_match()
: