user3395024
user3395024

Reputation: 153

regex Don't match the word after this one

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

Answers (1)

Amal Murali
Amal Murali

Reputation: 76646

Why doesn't your regex work?

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 > )".

How can it be fixed?

You can simply your regex as follows:

/Country: ([\w ]+)<br>/

Explanation:

  • / - starting delimiter
  • Country - 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 delimiter

The preg_match() statement would look like:

if (preg_match('//Country: ([\w ]+)<br>//', $exec, $matches)) {
    print_r($matches);
}

Upvotes: 1

Related Questions