从字符串中删除信息

时间:2012-09-08 13:59:11

标签: php regex string

我使用的API使用用户的IP地址来查找用户的国家/地区位置和城市,但我之前从未使用过正则表达式,我不知道如何提取我想要的其他信息。

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

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

 $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]; 

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

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

答案 2 :(得分:0)

一种方法是使用Country:,City:和IP:as delimiters。如果API始终返回所有三个字段,您可以一次性检索所有这些字段:

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

如果没有,您可能希望逐个提取它们:

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

就PHP部分而言,括号中的模式匹配在每个文档的matches数组中返回((?:和)之间的模式除外)。所以爱丁堡应该以$ match [2]的形式返回上面列出的第一个表达式。

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

相关问题