php字符串与通配符*匹配?

dyn*_*mic 30 php regex string-matching

我想给字符串和通配符匹配的可能性*.

$mystring = 'dir/folder1/file';
$pattern = 'dir/*/file';

stringMatchWithWildcard($mystring,$pattern);  //> Returns true
Run Code Online (Sandbox Code Playgroud)

例2:

$mystring = 'string bl#abla;y';
$pattern = 'string*y'; 

stringMatchWithWildcard($mystring,$pattern);  //> Returns true
Run Code Online (Sandbox Code Playgroud)

我想的是:

function stringMatch($source,$pattern) {
    $pattern = preg_quote($pattern,'/');        
    $pattern = str_replace( '\*' , '.*?', $pattern);   //> This is the important replace
    return (bool)preg_match( '/^' . $pattern . '$/i' , $source );
}
Run Code Online (Sandbox Code Playgroud)

基本上,更换*.*?(考虑*nix环境*相匹配empty的字符串) ©vbence

任何改进/暗示?

//添加return (bool)因为preg_match返回int

mar*_*rio 49

这里没有必要preg_match.PHP具有通配符比较功能,专门针对此类情况:

fnmatch()

并且fnmatch('dir/*/file', 'dir/folder1/file')可能已经为你工作了.但要注意,*通配符同样会添加更多的斜杠,就像preg_match一样.

  • 非POSIX系统不支持fnmatch.(我看到php5.3 +现在也支持windows).所以这并不总是最好的方式 (5认同)