我试图使用正则表达式来捕获文本行中的IP地址。现在它搞砸了。当文本行不包含ip地址时,我的代码返回ip地址,有时它返回" Script)"。我究竟做错了什么?我想返回实际拥有它们的行的IP地址,如果他们没有,则不返回任何内容。
文本
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>";
输出
207.230.229.204
207.230.229.204
207.230.229.204
207.230.229.204
207.230.229.204
Script)
答案 0 :(得分:13)
考虑删除字符串^
的开头和字符串$
的结尾,看看你的IP地址不在你提供的文本中字符串的开头/结尾。
if (preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $line, $ip_match)) {
echo $ip_match[0];
}
如果您想要所有IP地址,请使用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]);