Checking for a character in a word in PHP

In my program, you are mainly allowed to use only words containing the letters "IOSHZXN". I am trying to figure out the way you can mix letters and it will recognize that it matches. For example, the word SHINT does not match because it has a T, but the word SHINX matches because it contains only a combination of the letters listed (IOSHZXN)

<?php

        $word = "IOSHZNX";

        $charactersallowed = "IOSHZXN";

        if (preg_match('/IOSHZXN/', $word)) {
            echo "YES";
        } else {
            echo "NO";
        }



    ?>

Any help would be appreciated.

+3
source share
2 answers

You can do it:

It matches any that is not one of these letters and returns the opposite:

if (!preg_match('/[^IOSHZXN]+/', $word)) {
    echo "YES";
}

Also, if you want it to be case insensitive, you can use:

if (!preg_match('/[^IOSHZXN]+/i', $word)) {
    echo "YES";
}
  • [^...] matches any that is not defined in parentheses.
  • + .
  • i , .
+1

:

if (preg_match('/^[IOSHZXN]+$/', $word)) {

^ $ , IOSHZXN.

+2

All Articles