Search code examples
phpstringpreg-matchwords

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.


Solution

  • 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;
    }