繁体   English   中英

php preg match中的“ *”和“?”有什么区别?

[英]What's the difference between “*” and “?” in php preg match?

使用“ *”或“?”之间有区别吗? 在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

资料来源:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM