Need Help with PHP and REGEX

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
o0110o
Forum Newbie
Posts: 5
Joined: Sun Feb 14, 2010 2:55 pm

Need Help with PHP and REGEX

Post 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 :)
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Need Help with PHP and REGEX

Post 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.
o0110o
Forum Newbie
Posts: 5
Joined: Sun Feb 14, 2010 2:55 pm

Re: Need Help with PHP and REGEX

Post 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 :)
Post Reply