Array search with wildcard
Posted: Sun Jan 04, 2009 3:10 pm
Because I want to cut down on database use, both to reduce storage space required and the number of queries performed, I needed to find a way to see if a user's IP address has been banned. I figured the easiest way for this to work is if each banned IP addresses is placed in an array. However, I ran into the problem of not being able to use a wildcard, as I could have in a database. So, I wrote this script. Keeping in line with my simplistic approach to coding, it's very short. Any criticism of it would be appreciated.
Before writing this code myself, I tried searching the internet for it and found that others have this same problem. They, though, seek to compare a string with an array, whereas I am doing the opposite. So, for those people, I wrote this:
Code: Select all
function ban($address) {
$ban = array(
0 => '255.255.255.255',
1 => '250.250.250'
);
for ($i = 0; $i < sizeof($ban); $i++) {
if (eregi('^'.$ban[$i], $address)) {
return true; break;
}
}
}
Code: Select all
function search_array($search, $array, $type) {
switch ($type) {
case (1): // Wildcard at both ends of the string
$one = '';
$two = '';
break;
case (2): // Wildcard at the end of the string
$one = '^';
$two = '';
break;
case (3): // Wildcard at the start of the string
$one = '';
$two = '$';
break;
default: // No wildcard (if wrong type specified)
$one = '^';
$two = '$';
break;
}
for ($i = 0; $i < sizeof($array); $i++) {
if (eregi($one.$search.$two, $array[$i])) {
return true; break;
}
}
}