Need Help with PHP REGEX


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Need Help with PHP REGEX
# 1  
Old 02-16-2010
Need Help with PHP REGEX

Hello, I have this script:
Code:
<?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:
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.

What I'm aiming to do is make the regex change after this line:
Code:
$geo = file_get_contents("http://api.hostip.info/get_html.php?ip=$ip");

and before this line:
Code:
$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.

Regex seems to work differently with PHP, and I don't have much experience with regex or arrays; I'm just learning as I go Smilie
Any help would be greatly appreciated. Thanks Smilie

Last edited by o0110o; 02-16-2010 at 02:26 AM.. Reason: Additional Information
# 2  
Old 02-16-2010
Before using preg_match() on your $results, one approach would be split your $results into an array using the "+" delimiter that is in the $results string first.

For this you would use explode().

Quote:
array explode ( string $delimiter , string $string [, int $limit ] )
So first do something like this:

Code:
$my_parts = explode ("+", $results);

Quote:
Country%3A+CANADA+%28CA%29%0ACity%3A+ST.+JOHN%27S%2C+NL%0AIP%3A+142.162.13.207%0A
Resulting in:

Code:
$my_part[0]= Country%3A
$my_part[1]= CANADA
$my_part[2]= %28CA%29%0ACity%3A
$my_part[3]= ST.
$my_part[4]= JOHN%27S%2C  
$my_part[5]= NL%0AIP%3A
$my_part[6]= 142.162.13.207%0A

Or you could explode on ""%3A+" like this:


Code:
$my_parts = explode ("%3A+", $results);

Quote:
Country%3A+CANADA+%28CA%29%0ACity%3A+ST.+JOHN%27S%2C+NL%0AIP%3A+142.162.13.207%0A
Resulting in:

Code:
$my_part[0]= Country
$my_part[1]= CANADA+%28CA%29%0ACity
$my_part[2]= ST.+JOHN%27S%2C+NL%0AIP
$my_part[3]= 142.162.13.207%0A

If you explode() twice, I think you can get the substrings you are looking for without preg_match(), then combine them, of course. Or you can simply preg_replace() the offending "IP" with "" at the end of $my_part[2] ... up to you.

It might work for you to simply explode() on "%3A" first, it's up to you (not sure of your final output.. but it seems "%3A+" is best). Your string:

Quote:
Country%3A+CANADA+%28CA%29%0ACity%3A+ST.+JOHN%27S%2C+NL%0AIP%3A+142.162.13.207%0A
Code:
$my_part[0]= Country
$my_part[1]= +CANADA+%28CA%29%0ACity
$my_part[2]= +ST.+JOHN%27S%2C+NL%0AIP
$my_part[3]= +142.162.13.207%0A

Hopefully, I did not make too many "cut and paste" errors in my examples!
# 3  
Old 02-16-2010
[RESOLVED]
file_get_contents() and preg_match() did the trick Smilie

Thanks for all your help!
# 4  
Old 02-16-2010
Post your code so we can see it Smilie
# 5  
Old 02-16-2010
Quote:
Originally Posted by Neo
Post your code so we can see it Smilie
Rough Copy:
Code:
<?php

function getWeather($ip=false) {
    
   if (!empty($_SERVER['HTTP_CLIENT_IP']))
    {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $url = "http://api.hostip.info/get_html.php?ip=$ip";
    $geo = file_get_contents($url);
    if( preg_match('/City: (.*)\nIP:/', $geo, $matches) ){
        $results = $matches[1];
    }else{
        $results = 'getLocation failure';

    }

$location = urlencode($results);
$getAddress = "http://www.google.com/ig/api?weather=$location";
$xml_str = file_get_contents($getAddress,0);
$xml = new SimplexmlElement($xml_str);
$count = 0;
echo '<div id="weather">';
foreach($xml->weather as $item) {

foreach($item->forecast_information as $new) {
            echo $new->city['data'];
            }

        foreach($item->current_conditions as $new) {

            echo '<div class="weatherIcon">';
            echo '<img src="http://www.google.com/' .$new->icon['data'] . '"/><br/>';
        echo $new->condition['data'];
            echo $new->temp_f['data'];
            echo $new->temp_c['data'];
            echo $new->humidity['data'];
            echo $new->wind_condition['data'];
            echo '</div>';
            }

        foreach($item->forecast_conditions as $new) {

            echo '<div class="weatherIcon">';
            echo '<img src="http://www.google.com/' .$new->icon['data'] . '"/><br/>';
            echo $new->day_of_week['data'];
            echo $new->condition['data'];
            echo $new->low['data'];
            echo $new->high['data'];
            echo '</div>';
            }

    }

echo '</div>';
}

getWeather();

?>

Thanks!

Last edited by o0110o; 02-16-2010 at 02:42 PM.. Reason: Typo
# 6  
Old 02-16-2010
Looks good. Thanks for posting.

---------- Post updated at 18:51 ---------- Previous update was at 18:48 ----------

OBTW, your code will run faster if you download and install GeoIP vs call across the net to HostIP each time.
# 7  
Old 02-16-2010
Quote:
Originally Posted by Neo
Looks good. Thanks for posting.

---------- Post updated at 18:51 ---------- Previous update was at 18:48 ----------

OBTW, your code will run faster if you download and install GeoIP vs call across the net to HostIP each time.

Can I install GeoIP in RED HAT Linux? My server runs RED HAT.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Sendmail K command regex: adding exclusion/negative lookahead to regex -a@MATCH

I'm trying to get some exclusions into our sendmail regular expression for the K command. The following configuration & regex works: LOCAL_CONFIG # Kcheckaddress regex -a@MATCH +<@+?\.++?\.(us|info|to|br|bid|cn|ru) LOCAL_RULESETS SLocal_check_mail # check address against various regex... (0 Replies)
Discussion started by: RobbieTheK
0 Replies

2. Shell Programming and Scripting

Perl, RegEx - Help me to understand the regex!

I am not a big expert in regex and have just little understanding of that language. Could you help me to understand the regular Perl expression: ^(?!if\b|else\b|while\b|)(?:+?\s+){1,6}(+\s*)\(*\) *?(?:^*;?+){0,10}\{ ------ This is regex to select functions from a C/C++ source and defined in... (2 Replies)
Discussion started by: alex_5161
2 Replies

3. Shell Programming and Scripting

PHP - Regex for matching string containing pattern but without pattern itself

The sample file: dept1: user1,user2,user3 dept2: user4,user5,user6 dept3: user7,user8,user9 I want to match by '/^dept2.*/' but don't want to have substring 'dept2:' in output. How to compose such regex? (8 Replies)
Discussion started by: urello
8 Replies

4. UNIX for Dummies Questions & Answers

read regex from ID file, print regex and line below from source file

I have a file of protein sequences with headers (my source file). Based on a list of IDs (which are included in some of the headers), I'd like to print out only the specified sequences, with only the ID as header. In other words, I'd like to search source.txt for the terms in IDs.txt, and print... (3 Replies)
Discussion started by: pathunkathunk
3 Replies

5. Shell Programming and Scripting

regex

hello, i'm quite new to regex and Perl in general. What i need is a regex that does this trasformatiuon: input : S45020:97,0; S45020:45,1; output : crrout:97; errout:45; there are some other combination but they're useless for the comprehension of the regex i need I need it for some... (2 Replies)
Discussion started by: perdidohate
2 Replies

6. UNIX for Advanced & Expert Users

Vi Regex help

Can someone tell me what is going with this expression :%s/<C-V><C-M>/. Is there a way to get a more useful message if the carriage return has been deleted? http://objectmix.com/editors/149245-fixing-dos-line-endings-within-vim.html#post516826 Why does this expression work for... (1 Reply)
Discussion started by: cokedude
1 Replies

7. Shell Programming and Scripting

Converting perl regex to sed regex

I am having trouble parsing rpm filenames in a shell script.. I found a snippet of perl code that will perform the task but I really don't have time to rewrite the entire script in perl. I cannot for the life of me convert this code into something sed-friendly: if ($rpm =~ /(*)-(*)-(*)\.(.*)/)... (1 Reply)
Discussion started by: suntzu
1 Replies

8. Shell Programming and Scripting

REGEX help

Hi Guys, I'm trying to write a script that will strip out a session id from an html webpage. I am missing something on the regex for parsing a variable. I am trying to get just the alpha-numeric value for scriptSessionId from this text: <script type="text/javascript">if(!JAWR){var JAWR =... (2 Replies)
Discussion started by: tank126
2 Replies

9. Shell Programming and Scripting

regex help

I would like to search strings composed by only one type of charachter for example only strings composed by the charachter 'b' is it right? $egrep '\<(b+)+\>' filename Could be there some side effects? Regards. (1 Reply)
Discussion started by: and77
1 Replies

10. Shell Programming and Scripting

Regex

Hello I need to make a regex. I have a file myfile, in this file I want to find a number situated after PAYSLOT= Before PAYSLOT is the begining of line (I guess ^) and after the number is the end of line (I guess $) . I want to echo this number (I guess $1) and put it in my variable payslot.... (5 Replies)
Discussion started by: pppswing
5 Replies
Login or Register to Ask a Question