Php 获取数组字符串的一部分
您好,我的输出PHP代码是:Php 获取数组字符串的一部分,php,location,geo,geoip,locate,Php,Location,Geo,Geoip,Locate,您好,我的输出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 [st
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会出现这种情况,但我不知道现在有什么更好的解决方案。substr可能是最简单的:
$bad_country = 'BG - Bulgaria';
$good_country = substr($bad_country, 5); // start at char 5, 'B'
如果国家/地区与首字母缩略词总是以“-”分隔,请按以下方式操作:
list($acrn, $country) = explode(' - ', $var);
如果保证输出的格式始终相同(即BG-保加利亚、美国-美国等),则可以使用
explode()
:
这将输出“保加利亚”。请尝试:
foreach( $list as $v) {
$temp = explode(' - ', $v);
$countries[] = $temp[1];
}
当您的模式更改为以下模式时,请尝试此模式:
'#Country: [a-z]{2,} - (.*?) #i'
假设模式不会改变u已经有了模式,我想您不想使用preg\u replace或substr,因为它会增加额外的不必要的计算
$patterns["country"] = '#Country:.*-\s+(\w+?) #i';
'#Country: [a-z]{2,} - (.*?) #i'