我想提供将字符串与通配符 * 匹配的可能性.
I want to give the possibility to match string with wildcard *.
示例
$mystring = 'dir/folder1/file'; $pattern = 'dir/*/file'; stringMatchWithWildcard($mystring,$pattern); //> Returns true示例 2:
$mystring = 'string bl#abla;y'; $pattern = 'string*y'; stringMatchWithWildcard($mystring,$pattern); //> Returns true我的想法是这样的:
function stringMatch($source,$pattern) { $pattern = preg_quote($pattern,'/'); $pattern = str_replace( '\*' , '.*?', $pattern); //> This is the important replace return (bool)preg_match( '/^' . $pattern . '$/i' , $source ); }基本上将*替换为.*?(考虑在*nix环境中*匹配empty 字符串) ©vbence
Basically replacing * to .*? (considering in *nix environment * matches empty string) ©vbence
任何改进/建议?
//添加了 return (bool) 因为 preg_match 返回 int
// Added return (bool) because preg_match returns int
推荐答案这里不需要 preg_match.PHP 有一个通配符比较功能,专门针对这种情况:
There is no need for preg_match here. PHP has a wildcard comparison function, specifically made for such cases:
fnmatch()
而且 fnmatch('dir/*/file', 'dir/folder1/file') 可能已经对你有用了.但要注意 * 通配符同样会添加更多斜线,就像 preg_match 一样.
And fnmatch('dir/*/file', 'dir/folder1/file') would likely already work for you. But beware that the * wildcard would likewise add further slashes, like preg_match would.
更多推荐
php 字符串匹配通配符 *?
发布评论