Recently been explerimenting with regular expressions and when I\'ve tried to confirm that the preg_match()
function was not returning the expected result (
To avoid any partial matches, you must use anchors:
^
- start of a string$
- end of string.So use
$pattern = "/^(?:Banana|Apples)$/i";
See demo
Since you have an alternative list, you need to group them so that the anchors apply correctly, not just to the first and last alternatives. If you use "/^Banana|Apples$/i"
, banana
will be matched in bananas
and apples
in =apples
.
To only group alternatives but not store in any capture groups, a non-capturing group can be used ((?:....)
). Moreover, you do not need capturing groups set on the entire pattern since the whole match text is always stored inside Group 0.