使用PHP的preg_match来查看值是否与值列表匹配

I want to see if a variable contains a value that matches one of a few values in a hard-coded list. I was using the following, but recently found that it has a flaw somewhere:

if (preg_match("/^(init)|(published)$/",$status)) {
    echo 'found';
} else {
    echo 'nope';
}

I find that if the variable $status contains the word "unpublished" there is still a match even though 'unpublished' is not in the list, supposedly because the word 'unpublished' contains the word 'published', but I thought the ^ and $ in the regular expression are supposed to force a match of the whole word. Any ideas what I'm doing wrong?

^ matches the beginning of a string. $ matches the end of a string.

However, regexes are not a magic bullet that need to get used at every opportunity.

In this case, the code you want is

if ( $status == 'init' || $status == 'published' )

If you are checking against a list of values, create an array based on those values and then check to see if the key exists in the array.

Modify your pattern:

$pattern = "/^(init|published)$/";
$contain = "unpublished";

echo preg_match($pattern, $contain) ? 'found' : 'nope' ;

This pattern says our string must be /^init$/ or /^published$/, meaning those particular strings from start to finish. So substrings cannot be matched under these constraints.

In this case, regex are not the right tool to use.

Just put the words you want your candidate to be checked against in an array:

$list = array('init', 'published');

and then check:

if (in_array($status, $list)) { ... }