在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
// matches the letter "a" followed by zero or more "t" characters
// matches the letter "a" followed by a "t" character that may or may not be present
来源:你