正在从字符串中删除信息


Removing information from a string

我使用的是API,它使用用户的IP地址来查找用户的国家/地区和城市,但我以前从未使用过regex,也不知道如何提取我想要的其他信息。

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

此行返回'Country:UNITED KINGDOM(GB)City:Edinburgh IP:80192.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]; 

根据millimouse的建议,它看起来是这样的:

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

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

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

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

或者如果没有,你可能想一个接一个地提取它们:

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

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

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