Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rubanraj54/8d2071f2ebe2c592e70aba63857b83e6 to your computer and use it in GitHub Desktop.
Save rubanraj54/8d2071f2ebe2c592e70aba63857b83e6 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
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment