delete acc
delete acc

Reputation: 167

Checking if a character is in a word in PHP

In my program basically your only allowed to use words that contain the letters "IOSHZXN" I'm trying to figure out a way where you can mix up the letters and it will recognize that it matches. For example, word SHINT does not match since it has a T, but the word SHINX matches because it contains only the 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..

Upvotes: 3

Views: 50

Answers (2)

Anonymous
Anonymous

Reputation: 12027

You can do this:

It matches anything that is not one of those 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";
}
  • The [^...] matches anything that is not defined within the brackets.
  • The + continues to search through the entire string.
  • The i makes it not care about if letters are capitalized or not.

Upvotes: 1

xdazz
xdazz

Reputation: 160963

You should use:

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

^ and $ make sure the string only the a combination of letters IOSHZXN.

Upvotes: 2

Related Questions