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 | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've added
'/'as a second argument inpreg_quotedue to error if/character exists in wildcard.fnmatchis not acceptable because offilename exceeds the maximum allowed length of 2048 characterserror on long $haystack strings.