2

我正在使用一个 API,它使用用户 IP 地址来找出用户的国家位置和城市,但是我以前从未使用过正则表达式,我不知道如何提取我想要的其他信息。

    $location=file_get_contents('http://api.hostip.info/get_html.php?ip='.$ip);

此行返回“国家:英国(GB)城市:爱丁堡 IP:80.192.82.75 ”我已设法使用正则表达式提取 IP 地址,但不知道如何将国家和城市删除为单独的变量($country = , $城市=)。这是我到目前为止的代码。

 $ip=$_SERVER['REMOTE_ADDR'];
 $location=file_get_contents('http://api.hostip.info/get_html.php?ip='.$ip);
 preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $location, $matches); 
 $ip = $matches[0]; 
4

3 回答 3

1

接受millimoose的建议,它看起来像这样:

$jstring = file_get_contents('http://api.hostip.info/get_json.php?ip='.$ip);
$ipinfo = json_decode($jstring);

这给出了:

stdClass Object
(
    [country_name] => NETHERLANDS
    [country_code] => NL
    [city] => (Unknown city)
    [ip] => xx.xx.10.9
)

这可以用作:

echo $ipinfo->city;
于 2012-09-08T14:06:32.897 回答
0

使用正则表达式模式/Country: ([^\(]+) \(([^\)]+)\) City: ([^:]+) IP: ([\d.]+)/

于 2012-09-08T14:14:18.027 回答
0

一种方法是使用 Country:、City: 和 IP: 作为分隔符。如果 API 总是返回所有三个字段,您可以一次性检索所有字段:

/^Country: (.*?) City: (.*?) IP: (.*?)$/

或者,如果没有,您可能需要一一提取它们:

/Country: (.*?)(?: \w+?:)?/
/City: (.*?)(?: \w+?:)?/
/IP: (.*?)(?: \w+?:)?/

就 PHP 部分而言,括号中模式的匹配项根据文档在匹配数组中返回(除了 (?: 和 ) 之间的模式)。因此,对于我上面列出的第一个给定表达式,应该在 $matches[2] 中返回 Edinburgh。

请注意,我相信上述字符串可能需要额外的转义,特别是如果它们放在双引号中。

于 2012-09-08T14:20:17.463 回答