Why preg_match() always validates as true when partial match?

前端 未结 1 1070
误落风尘
误落风尘 2021-01-07 02:03

Recently been explerimenting with regular expressions and when I\'ve tried to confirm that the preg_match() function was not returning the expected result (

相关标签:
1条回答
  • 2021-01-07 02:40

    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.

    0 讨论(0)
提交回复
热议问题