-1

Hello my output PHP code is :

Array ( [country] => BG - Bulgaria )

... and he comes from here :

<?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: (.*?)&nbsp;#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;
       }

?>

How can I get ONLY the name of the Country like in my case "Bulgaria"? I think it will happen with preg_replace or substr but i dont know what is the better solution now.

SZ4
  • 61
  • 2
  • 9

6 Answers6

2

substr's probably easiest:

$bad_country = 'BG - Bulgaria';
$good_country = substr($bad_country, 5); // start at char 5, 'B'
Marc B
  • 356,200
  • 43
  • 426
  • 500
0

if the country is always separated from the acronym by ' - ', do it like this:

list($acrn, $country) = explode(' - ', $var);
dnagirl
  • 20,196
  • 13
  • 80
  • 123
0

If you are guaranteed that the output will always be in the same format(ie BG - Bulgaria, US - United States, etc), you could use explode():

$array['country'] = "BG - Bulgaria";
$country = explode(" - ", $array['country']);
echo $country[1];

This will output "Bulgaria".

JustAPoring
  • 258
  • 1
  • 12
0

try:

    foreach( $list as $v) {
     $temp = explode(' - ', $v);        
     $countries[] = $temp[1];
}
Teena Thomas
  • 5,139
  • 1
  • 13
  • 17
0
$patterns["country"] = '#Country:.*-\s+(\w+?)&nbsp;#i';

try this one as your pattern

Surace
  • 701
  • 3
  • 8
  • u already have pattern and i guess you dont want to use preg_replace or substr as it will add extra unnecessary computaion – Surace Sep 26 '12 at 15:50
0

Change your pattern to this:

'#Country: [a-z]{2,} - (.*?)&nbsp;#i'

Assuming the pattern won't change

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309