Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - regex to return ip addresses from lines of text

Tags:

regex

php

I'm trying to use a regex to capture ip addresses in lines of text. Right now it's kind of screwed up. My code returns ip addresses when lines of text don't contain ip addresses and sometimes it returns "Script)". What am I doing wrong? I would like to return the ip addresses of lines that actually have them, and return nothing if they don't.

Text

2014-06-02 11:53:54.410 -0700   Information 638 NICOLE  Client "123456" opening a connection from "123456.local (207.230.229.204)" using "Go 13.0.4 [fmapp]".
2014-06-02 11:54:52.504 -0700   Information 98  NICOLE  Client "123456 (123456.local) [207.230.229.204]" closing database "FMServer_Sample" as "Admin".
2014-06-02 12:07:33.433 -0700   Information 638 NICOLE  Client "[WebDirect]" opening a connection from "207.230.229.204 (207.230.229.204)" using "Win Chrome 35.0 [fmwebdirect]".
2014-06-02 13:05:00.088 -0700   Information 638 NICOLE  Client "Showare Update" opening a connection from "FileMaker Script" using "Server 13.0v1 [fmapp]".
2014-06-02 13:05:22.366 -0700   Information 98  NICOLE  Client "Showare Update (FileMaker Script)" closing database "cac" as "opus".
2014-06-02 12:08:04.165 -0700   Information 98  NICOLE  Client "[WebDirect] (207.230.229.204) [207.230.229.204]" closing database "FMServer_Sample" as "Admin".

PHP

if(preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $line, $ip_matches)) {
    $client_ips = $ip_matches[1];
}

print "<pre>;
print_r($client_ips);
print "</pre>";

Output

207.230.229.204
207.230.229.204
207.230.229.204
207.230.229.204
207.230.229.204
Script)
like image 284
Aaron Turecki Avatar asked Jun 09 '14 02:06

Aaron Turecki


1 Answers

Consider removing the beginning of string ^ and end of string $ anchors seeing how your IP addresses are not at the beginning/end of the string in your provided text.

if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $line, $ip_match)) {
   echo $ip_match[0];
}

If you want all IP addresses, use preg_match_all()

preg_match_all('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $line, $ip_matches);
print_r($ip_matches[0]);
like image 84
hwnd Avatar answered Oct 21 '22 05:10

hwnd