extracting line containing an IP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

extracting line containing an IP

Post by nigma »

Hey, anyone show me how to extract an entire line that contains an IP address?

if I had four lines like this:
Bob had something that I wanted
he then took it to my house
which I sometimes call 127.0.0.1
or home.

I would want to store the third line in a variable.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Code: Select all

<?php
$lines = file('test.data.txt');
$pattern = '!\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b!';
$store = array();

foreach($lines as $line)
{
	if (preg_match($pattern, $line))
		$store[] = $line;
}
?>
<pre><?php print_r($store); ?></pre>
\b word boundary
\d{1,3} one to three digits
\. a dot (escaping the special meaning of . in a pattern)
[]InTeR[]
Forum Regular
Posts: 416
Joined: Thu Apr 24, 2003 6:51 am
Location: The Netherlands

Post by []InTeR[] »

I think the best way to find this is to use Regular Expression's.

I'm not a herro in regular expressions but maybe somebody else is.
Drachlen
Forum Contributor
Posts: 153
Joined: Fri Apr 25, 2003 1:16 am

Post by Drachlen »

Code: Select all

<?php
$str = $_SERVER["REMOTE_ADDR"] . " | " . $_SERVER["HTTP_USER_AGENT"] . "\n"; 

$fp = fopen("./log.txt", "a+"); 


fputs($fp, $str); 


fclose($fp); 
?>
I had no idea what volka said, so here is a much less complicated version, you can simply delete the user agent if you want, when visiting this page it logs it to log.txt, if you want it to display it on the page, do something like

Code: Select all

<?php
echo "Your IP is $_SERVER[REMOTE_ADDR]";
?>
But this way it isnt saving it anywhere, its gone once ye exit ;)
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

I don't think the user's ip was meant but any line of a (undefined) source that contains one or more IPs somewhere.
Post Reply