Forum Moderators: coopster

Message Too Old, No Replies

Matching text in an array

matching text in an array

         

Tourex

7:53 pm on May 18, 2005 (gmt 0)

10+ Year Member



I know this is a really easy one, but its been a long day and the old brain has packed up.

I've got an array with the main keys for a number of IP addresses, as follows:

$IP = array();
$IP[] = "216.239.46.";
$IP[] = "216.239.3";
$IP[] = "216.200.130.";
$IP[] = "216.35.116";
$IP[] = "216.35.112.";
$IP[] = "216.34.121.";

Now, the string $ip_address contains the full IP address of someone visiting the site. I want to compare it with the list above and tell if it is a crawler.

What code should I use from here? I've tried various things, but found nothing that works reliably. I know I'm missing something obvious and hope somebody will put me straight.

Thanks.

mcibor

10:08 pm on May 18, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The best function in my opinion would be : in_array(). More about it you will find on [pl.php.net...]

Best wishes
Michal Cibor

PS. You need to get rid of the last dot in your IP strings

StupidScript

11:24 pm on May 18, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



mcibor is right in that
in_array()
will let you know if the string you seek is in the array. You would need to clip the IP address to compare against to get the fragments you have in your array.

It would be slightly less processor-intensive if you were to compare to the reverse, i.e. instead of looking for the IP string (fragment) in the array, check the array elements against the full IP. That way you could break the comparison when the fragment was found in the IP, rather than executing the fragmentation of the full IP and then forcing PHP to walk the entire array each time.

foreach($listarray as $x) {

if (eregi($x,$IP_address)) {

#Found it, so do bot stuff then

break;

}

}

Rather than:

$ipfrags=explode(".",$IP_address);

$frag=$ipfrags[0].".".$ipfrags[1].".".$ipfrags[2];

if(in_array($frag,$listarray)) {

#Found it, so do bot stuff

}

Just a performance thought. (in_array() doesn't scale well when the array gets too large ... and a bot array will get huge!)