Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php check if string contains multiple words

I have looked around the internet for something that will do this but it will only work with one word.

I am trying to build a script that will detect a bad username for my site, the bad username will be detected if the username contains any of the words in an array.

Here's the code I made, but failed to work.

$bad_words = array("yo","hi");
$sentence = "yo";

if (strpos($bad_words,$sentence)==false) {
echo "success";
}

If anybody could help me, I would appreciate it.

like image 975
Frank Avatar asked Aug 30 '26 17:08

Frank


2 Answers

use

substr_count

for an array use the following function

function substr_count_array( $haystack, $needle ) {
     $count = 0;
     foreach ($needle as $substring) {
          $count += substr_count( $haystack, $substring);
     }
     return $count;
}
like image 81
Oliver M Grech Avatar answered Sep 02 '26 06:09

Oliver M Grech


You can use this code:

$bad_words = array("yo","hi");
$sentence = "yo you your";
// break your sentence into words first
preg_match_all('/\w+/', $sentence, $m);
echo ( array_diff ( $m[0], $bad_words ) === $m[0] ) ? "no bad words found\n" :
                                                      "bad words found\n";
like image 36
anubhava Avatar answered Sep 02 '26 05:09

anubhava