7

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)
3
  • You're overwriting $client_ips on every loop iteration. A variable can only contain one value at once. Commented Jun 9, 2014 at 2:15
  • 1
    ..unless its an array $client_ips[] = $ip_matches[1]; Commented Jun 9, 2014 at 2:16
  • 1
    And that's not the actual regex you used. The ^ anchors $ wouldn't make it match on any line. Commented Jun 9, 2014 at 2:24

1 Answer 1

21

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]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.