PHP Wildcard Match in an Array
Posted by Matt on 30th November 2006
I was working with a list of wildcard banned domain names (e.g. *.spamsite.com) stored in a database. I needed to compare a submitted domain (e.g. anything.spamsite.com) to the wildcard entries stored in the database.
Essentially then I need the function in_array to perform with a wildcard match with the wildcards being the array haystack not the needle.
In the above example, I need the script to detect that anything.spamsite.com is banned. Here’s what I did:
-
$bannedurl = false;</p>
-
//The function fnmatch is useful here but is not available on Windows systems, so it must be defined if it does not exist.
-
-
return @preg_match(‘/^’ . strtr(addcslashes($pattern, ‘\\.+^$(){}=!<>|’), array(‘*’ => ‘.*’, ‘?’ => ‘.?’)) . ‘$/i’, $string);
-
}
-
}
-
-
//This function allows wildcards in the array to be searched
-
function my_inArray($needle, $haystack) {
-
foreach ($haystack as $value) {
-
return true;
-
}
-
}
-
return false;
-
}
-
foreach ($wild_urls as $value) {
-
$wild_urls[] = ‘*’ . $value;
-
}
-
-
//An Example
-
-
$domain = ‘anything.spamsite.com’;
-
-
//Test it, returns true if the Domain is banned.
-
-
if (my_inArray($domain, $wild_urls)) $bannedurl = true;
-
-
//Note, for the domain spamsite.com, you can do a straight MySQL query such as " …… where domain like ‘%" . $domain . "’ and domain not like ‘%_." . $domain . "’ "
Posted in MySQL, PHP Code Snippets | No Comments »