Created
December 19, 2012 21:34
-
-
Save irazasyed/4340734 to your computer and use it in GitHub Desktop.
PHP: Match wildcard in string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
); |
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
Why not use
fnmatch