php string matching with wildcard *?

dynamic picture dynamic · May 28, 2011 · Viewed 57.7k times · Source

I want to give the possibility to match string with wildcard *.

Example

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

stringMatchWithWildcard($mystring,$pattern);  //> Returns true

Example 2:

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

stringMatchWithWildcard($mystring,$pattern);  //> Returns true

I thought something like:

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

Basically replacing * to .*? (considering in *nix environment * matches empty string) ©vbence

Any improvments/suggests?

// Added return (bool) because preg_match returns int

Answer

mario picture mario · May 28, 2011

There is no need for preg_match here. PHP has a wildcard comparison function, specifically made for such cases:

fnmatch()

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.