I need to check if a string contains any one of the banned words. My requirements are:
stripos()
I have tried something like below
$string = "poker park is great";
if (stripos($string, 'poker||casino') === false)
{
echo "banned words found";
}
else
{
echo $string;
}
You can use some() function: to check if a string contains any element of an array. e.g. var fruitsArr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange']; var myString = "I have an apple and a watermelon."; var stringIncludesFruit = fruitsArr. some(fruit => myString.
Using String. contains() method for each substring. You can terminate the loop on the first match of the substring, or create a utility function that returns true if the specified string contains any of the substrings from the specified list.
The simplest way to check if a string contains a substring in Python is to use the in operator. This will return True or False depending on whether the substring is found. For example: sentence = 'There are more trees on Earth than stars in the Milky Way galaxy' word = 'galaxy' if word in sentence: print('Word found.
Use preg_match to match a regular expression:
$string = "poker park is great";
if (preg_match("/(poker|casino)/", $string)) {
echo "banned words found";
} else {
echo $string;
}
UPDATE: As suggested in comments and in Mayur Relekar answer, if you want your match to be case-insensitive, you should add an i
flag to your regex.
And, if you want to match words (i.e., "poker" should be preceded and followed by a word-boundary, for example a space, a punctuation, or an end-of-file), you should enclose your matching group with \b
...
So:
...
if (preg_match("/\b(poker|casino)\b/i", $string)) {
...
MarcoS is right, except that in your case you need to match the exact string and not an unbound string. For this, you need to prefix and suffix \b
(\b
is a word delimiter) to the string you want to exactly match.
$string = "poker park is great";
if (preg_match("/\bpoker\b/", $string)) {
echo "banned words found";
} else {
echo $string;
}
$string = "park doing great with pokering. casino is too dangerous.";
$needles = array("poker","casino");
foreach($needles as $needle){
if (preg_match("/\b".$needle."\b/", $string)) {
echo "banned words found";
die;
}
}
echo $string;
die;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With