最近尝试使用正则表达式,并尝试确认 preg_match()
函数未返回预期结果 (false
)。我意识到我的正则表达式在部分匹配和完全匹配的情况下都会评估为 true。
任何更有经验的人都可以分享一些关于为什么会这样的评论吗?
我已经使用以下代码对此进行了测试:
<?php
# Storing regexp.
$pattern = "/Banana|Apples/i";
# Storing value that will be compared against regexp.
$value = "Chiiiiiiiibanana";
# Testing how preg_match is dealing with the regexp.
if (preg_match($pattern, $value, $matches)) {
echo "It's a match!\n";
# In case there's matches, print them.
print_r($matches);
} else {
echo "Sorry, not a match.";
}
?>
在这种情况下,正则表达式返回 1
(true),尽管“bananas
”作为前缀“Chiiiiiiii
”。有什么想法吗?
最佳答案
为了避免任何部分匹配,您必须使用 anchor :
^
- 字符串的开头$
- 字符串结尾。
所以使用
$pattern = "/^(?:Banana|Apples)$/i";
参见demo
由于您有一个替代列表,因此您需要对它们进行分组,以便正确应用 anchor ,而不仅仅是第一个和最后一个替代项。如果您使用 "/^Banana|Apples$/i"
,banana
将在 bananas
和 apples
中匹配在=苹果
中。
要仅对备选方案进行分组而不存储在任何捕获组中,可以使用非捕获组 ((?:....)
)。此外,您不需要在整个模式上设置捕获组,因为整个匹配文本始终存储在组 0 内。
关于php - 为什么部分匹配时 preg_match() 总是验证为 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34318599/