使用"*"或"?"之间有区别吗?在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);
Run Code Online (Sandbox Code Playgroud)
* 匹配0或更多
? 匹配0或1
在您的特定测试的上下文中,您无法区分,因为*和?匹配没有锚定或没有任何跟随它们 - 它们都匹配任何包含a的字符串a,无论是否后跟t.
如果你在比赛角色之后有什么东西,差别很重要,例如:
echo preg_match("/at*z/", "attz"); // true
echo preg_match("/at?z/", "attz"); // false - too many "t"s
Run Code Online (Sandbox Code Playgroud)
而与你的:
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
Run Code Online (Sandbox Code Playgroud)