PHP on Linux – test to see if a string with wildcards (*) matches another string

This function is useful to test if an IP belongs to an IP class (for example: 192.168.*.*). It can also be used to integrate any kind of wildcard (*) string matching into your software.

The first argument for the function is the pattern with wildcards, and the second argument is the individual string to be tested against the version with wildcards for a match. For example $pattern can be “192.168.*.*” and $string can be “192.168.1.4”, in which case it would return a match.

The function returns TRUE if there is a match, and FALSE if there is no match.

function simplified_fnmatch($pattern, $string)
{
	// fnmatch is a function available on linux systems, which sees if a $pattern string with wildcards matches a string, using linux shell rules
	// the simplified_fnmatch function escapes ?,[], and {} characters, so as to only apply the * wildcard
	// it also uses the FNM_CASEFOLD flag, since in URLs case does not matter
	
	$escaped_pattern = '';
	for ($i = 0; $i < strlen($pattern); $i++)
	{
		if (($pattern[$i] == '?') || ($pattern[$i] == '[') || ($pattern[$i] == ']') || ($pattern[$i] == '{') || ($pattern[$i] == '}')) $escaped_pattern .= '\\';
		$escaped_pattern .= $pattern[$i];
	}
	return fnmatch($escaped_pattern, $string, FNM_CASEFOLD);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close