正则表达式匹配index.html,index.htm,default.html,default.htm

jef*_*kee 0 php regex

我正在从某个文件夹中检索一组文件,我想检测每个文件是否名为index.html,index.htm,default.html,default.htm等.而不是一个笨拙的行说

if($file=='index.html || $file=='index.htm' || $file=='INDEX.HTML')

我宁愿使用正确的正则表达式来匹配大写/小写变体等.任何帮助将不胜感激.

dev*_*odo 6

怎么样:

if (preg_match('/^(index|default)\.html?$/i', $file)) {
    echo 'file matches';
}
Run Code Online (Sandbox Code Playgroud)


Pek*_*ica 5

是不是真的值得吗?对于处理代码的其他人来说,正则表达式更难阅读,因此您最终会在评论中解释它,占用比原始解决方案更多的空间.

为什么不做一个strtolower()和正常的比较,也许缩写为使用in_array()

比如说

$names = array("index.htm", "index.html", "default.html", "default.htm");

if (in_array($file, $names))
 // do stuff
Run Code Online (Sandbox Code Playgroud)