Reputation: 153
I'm programming a tool that tell you which is the country of the IP but I have problem
This is the code that I tried
<?
$ip = "109.224.62.197";
$curl = curl_init();
CURL_SETOPT($curl,CURLOPT_URL,"http://www.ipligence.com/geolocation");
CURL_SETOPT($curl,CURLOPT_POSTFIELDS,"ip=".$ip);
CURL_SETOPT($curl,CURLOPT_RETURNTRANSFER,True);
CURL_SETOPT($curl,CURLOPT_FOLLOWLOCATION,True);
$exec = curl_exec($curl);
curl_close($curl);
$regex = "/Country: (.*)[^(<br>)]/";
if(preg_match($regex,$exec,$result)){
print_r($result);
}
?>
And this is the result that I got
Array ( [0] => Country: Iraq
Continent: Middle East
Time Zone: GMT+3 more demo?'; [1] => Iraq
Continent: Middle East
Time Zone: GMT+3 more demo?'; )
But I want only to match the country name Iraq and after that I don't want to display anything else
Upvotes: 1
Views: 115
Reputation: 76646
Your regular expression is as follows:
/Country: (.*)[^(<br>)]/
This will not work as you expect. (.*)
is a greedy match and will consume as many characters as possible, eating until the end of the line.
[^(<br>)]
is a negated character class, but it doesn't mean: "Match everything that's not a <br/>
". It means: "Match anything that's not in the list of characters ( < b r > )
".
You can simply your regex as follows:
/Country: ([\w ]+)<br>/
Explanation:
/
- starting delimiterCountry
- match the character sequence Country
case-sensitively[\w+ ]+
- match any word character ([a-zA-Z0-9_]
) or a literal space character one or more times<br>
- match the character sequence <br>
/
- ending delimiterThe preg_match()
statement would look like:
if (preg_match('//Country: ([\w ]+)<br>//', $exec, $matches)) {
print_r($matches);
}
Upvotes: 1