foreach交叉检查IP和echo'ing匹配

时间:2012-12-14 05:25:10

标签: php

我正在尝试检查$ userinfo [host](ip地址列表)是否在visitor.txt文件中有任何匹配项。如果是,则回显匹配的字符串

似乎没有任何回应。没有错误。

这是基本的txt文件

  208.54.22.144|1355385350
  208.54.14.235|1355386649
  69.151.178.16|1355386296

(编辑字符串)

$ips = file_get_contents('visitors.txt');
$ip_regex = '/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/';
foreach ($ips as $check){
preg_match($ip_regex, $check, $current_ip);
if ((strpos($userinfo['host'],$current_ip[0]) !== false)) {
echo $userinfo['host'];
}
}

2 个答案:

答案 0 :(得分:1)

你说你正在检查IP,但是,你现在的方式是比不仅仅是IP,例如说我的IP是127.0.0.1而在visitor.txt文件中我有一个有效的条目127.0.0.1 | 123456.在你的每个循环中,它看起来像这样:

if(127.0.0.1,127.0.0.1 | 123456)....

您可以尝试仅使用正则表达式比较IP来从当前文本行中分割出IP。例如:

$ips = file("visitors.txt");
echo "You are hosted at: ".$userinfo['host']."<br />";
$ip_regex = '/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/';
foreach ($ips as $check) {
    preg_match($ip_regex, $check, $current_ip);
    if ((strpos($userinfo['host'],$current_ip[0]) !== false)) {
        echo $userinfo['host'];
    }

}

答案 1 :(得分:0)

试试这个..

<?php
$ips = file_get_contents('test.txt');
if(strpos($ips, $userinfo['host']) !== FALSE)
{
  echo $userinfo['host'];
}
?>