Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php string matching with wildcard *?

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

like image 842
dynamic Avatar asked May 28 '11 17:05

dynamic


People also ask

What is a wildcard in PHP?

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.

How do I match a string in PHP?

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().

Can you use wildcard in regex?

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.

What is wildcard pattern matching?

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.


1 Answers

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.

like image 58
mario Avatar answered Oct 10 '22 23:10

mario