您好我的输出PHP代码是:
Array ( [country] => BG - Bulgaria )
......他来自这里:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
print_r(geoCheckIP($ip));
//Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => DE - Germany [state] => Hessen [town] => Erzhausen )
//Get an array with geoip-infodata
function geoCheckIP($ip)
{
//check, if the provided ip is valid
if(!filter_var($ip, FILTER_VALIDATE_IP))
{
throw new InvalidArgumentException("IP is not valid");
}
//contact ip-server
$response=@file_get_contents('http://www.netip.de/search?query='.$ip);
if (empty($response))
{
throw new InvalidArgumentException("Error contacting Geo-IP-Server");
}
//Array containing all regex-patterns necessary to extract ip-geoinfo from page
$patterns=array();
$patterns["country"] = '#Country: (.*?) #i';
//Array where results will be stored
$ipInfo=array();
//check response from ipserver for above patterns
foreach ($patterns as $key => $pattern)
{
//store the result in array
$ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : '';
}
return $ipInfo;
}
?>
我怎样才能获得国家的名称,就像我的情况“保加利亚”一样?我认为它会在preg_replace或substr中发生,但我现在不知道什么是更好的解决方案。
答案 0 :(得分:2)
substr可能最简单:
$bad_country = 'BG - Bulgaria';
$good_country = substr($bad_country, 5); // start at char 5, 'B'
答案 1 :(得分:0)
如果国家总是用' - '与首字母缩略词分开,请这样做:
list($acrn, $country) = explode(' - ', $var);
答案 2 :(得分:0)
如果您保证输出将始终采用相同的格式(即 BG - Bulgaria , US - United States 等),您可以使用{{ 1}}:
explode()
这将输出“保加利亚”。
答案 3 :(得分:0)
尝试:
foreach( $list as $v) {
$temp = explode(' - ', $v);
$countries[] = $temp[1];
}
答案 4 :(得分:0)
$patterns["country"] = '#Country:.*-\s+(\w+?) #i';
尝试将此作为您的模式
答案 5 :(得分:0)
将您的模式更改为:
'#Country: [a-z]{2,} - (.*?) #i'
假设模式不会改变