Skip to content

Instantly share code, notes, and snippets.

@irazasyed
Created December 19, 2012 21:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save irazasyed/4340734 to your computer and use it in GitHub Desktop.
Save irazasyed/4340734 to your computer and use it in GitHub Desktop.
PHP: Match wildcard in string
function match_wildcard( $wildcard_pattern, $haystack ) {
$regex = str_replace(
array("\*", "\?"), // wildcard chars
array('.*','.'), // regexp chars
preg_quote($wildcard_pattern)
);
return preg_match('/^'.$regex.'$/is', $haystack);
}
$test = "foobar and blob\netc.";
var_dump(
match_wildcard('foo*', $test), // TRUE
match_wildcard('bar*', $test), // FALSE
match_wildcard('*bar*', $test), // TRUE
match_wildcard('**blob**', $test), // TRUE
match_wildcard('*a?d*', $test), // TRUE
match_wildcard('*etc**', $test) // TRUE
);
@wxiaoguang
Copy link

Why not use fnmatch

@windbridges
Copy link

I've added '/' as a second argument in preg_quote due to error if / character exists in wildcard.
fnmatch is not acceptable because of filename exceeds the maximum allowed length of 2048 characters error on long $haystack strings.

function match_wildcard( $wildcard_pattern, $haystack ) {
   $regex = str_replace(
     array("\*", "\?"), // wildcard chars
     array('.*','.'),   // regexp chars
     preg_quote($wildcard_pattern, '/')
   );

   return preg_match('/^'.$regex.'$/is', $haystack);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment