Page 1 of 1

Need Help with PHP and REGEX

Posted: Mon Feb 15, 2010 11:40 pm
by o0110o
Hello, I have this script:

Code: Select all

 
<?php
 
function getLocation() {
$ip = $_SERVER['REMOTE_ADDR'];
$geo = file_get_contents("http://api.hostip.info/get_html.php?ip=$ip");
$results = urlencode($geo);
echo $results;
}
 
getLocation();
 
?>
 
Which returns:

Code: Select all

 
Country%3A+CANADA+%28CA%29%0ACity%3A+ST.+JOHN%27S%2C+NL%0AIP%3A+142.162.13.207%0A
 
I would like for $results to contain only "ST.+JOHN%27S%2C+NL"; in other words the city name and the province/state for the visiting user.
Unfortunately my experience with PHP REGEX is little to none and I've tried hard to make this work before posting here but my attempts were unsuccessful :(

Any help would be greatly appreciated. Thanks :)

Re: Need Help with PHP and REGEX

Posted: Tue Feb 16, 2010 12:11 am
by requinix
Why are you urlencode-ing it?

Code: Select all

Country: CANADA (CA)
City: ST. JOHN'S, NL
IP: 142.162.13.207
 
Try a regex for that, and if you can't get it, post what you have.

Re: Need Help with PHP and REGEX

Posted: Tue Feb 16, 2010 12:20 am
by o0110o
tasairis wrote:Why are you urlencode-ing it?

Code: Select all

Country: CANADA (CA)
City: ST. JOHN'S, NL
IP: 142.162.13.207
 
Try a regex for that, and if you can't get it, post what you have.

What I want to do is make the regex change after this line:

Code: Select all

 
$geo = file_get_contents("http://api.hostip.info/get_html.php?ip=$ip");
 
and before this line:

Code: Select all

 
$results = urlencode($geo);
 
This way the modified data (ie. "City%2C+State") gets passed off into $results.
I need $results encoded because this script is going to be part of another script where $results get passed off as part of a URL parameter.[/QUOTE]

I Have achieved something similar to this on the command line:

Code: Select all

 
curl -s api.hostip.info/get_html.php?ip=$(curl -s icanhazip.com) | sed -e'1d;3d' -e's/C.*: \(.*\)/\1/' -e's/ /%20/g' -e"s/'/%27/g" -e"s/-/%2d/g"
 
Regex seems to work differently with PHP, and I don't have much experience with arrays; I'm just learning as I go :)