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 “”, 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 *

three + four =

This site uses Akismet to reduce spam. Learn how your comment data is processed.