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
A wildcard character is used to substitute one or more characters in a string. Wildcard characters are used with the LIKE operator. The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().
In regular expressions, the period ( . , also called "dot") is the wildcard pattern which matches any single character. Combined with the asterisk operator . * it will match any number of any characters.
A wildcard pattern is a series of characters that are matched against incoming character strings. You can use these patterns when you define pattern matching criteria. Matching is done strictly from left to right, one character or basic wildcard pattern at a time.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With