使用“*”或“?”有区别吗?在 php preg_match 中?或者有例子吗?
<?php
// the string to match against
$string = 'The cat sat on the matthew';
// matches the letter "a" followed by zero or more "t" characters
echo preg_match("/at*/", $string);
// matches the letter "a" followed by a "t" character that may or may not be present
echo preg_match("/at?/", $string);
最佳答案
*
匹配 0 个或多个
?
匹配 0 或 1
在您的特定测试的上下文中,您无法分辨出差异,因为 *
和 ?
匹配项未锚定或没有任何内容跟随它们 -它们都会匹配任何包含 a
的字符串,无论是否后跟 t
。
如果您在匹配字符之后有一些东西,那么差异很重要,例如:
echo preg_match("/at*z/", "attz"); // true
echo preg_match("/at?z/", "attz"); // false - too many "t"s
而对于你的:
echo preg_match("/at*/", "attz"); // true - 0 or more
echo preg_match("/at?/", "attz"); // true - but it stopped after the
// first "t" and ignored the second
https://stackoverflow.com/questions/9040435/