比较PHP中的路径字符串与通配符


Comparing Path String With Wildcard in PHP

如何比较此字符串:

commodity/search/oil/branch/index

这个:

commodity/search/*/branch/index

它应该返回true,尽管"oil"被替换为其他单词。

$match = preg_match("/commodity'/search'/(.*)'/branch'/index/", "commodity/search/someotherword/branch/index");

如果找到匹配,则$match将为true(或某个评估为true的值,如1)。

注意:以上内容将在任何额外的路径上匹配,例如commodity/search/some/other/word/branch/index

如果你只想匹配一个单词,但不想匹配类似路径结构的单词,那么你可以尝试这样的方法:

$match = preg_match("/commodity'/search'/[A-Za-z0-9_-]+'/branch'/index/", "commodity/search/some-OTHER_word/branch/index");

这将只匹配大小写a-z字符、数字、连字符和下划线。根据需要进行调整。

PHP有一个内置的函数,称为fnmatch()。

它提供了基本通配符的用法。

<?php
if (fnmatch('commodity/search/*/branch/index', 'commodity/search/oil/branch/index')) {
    echo "It matches!";
}

不过,在非POSIX兼容的系统上不支持它(请参阅PHP手册)。