tags:

views:

122

answers:

3

i have variable $result that contains this

Country: USA City: NY Latitude: 32.2667 Longitude: 71.9167

How do I parse it so I can get the out put like this:

Country=USA&City=NY&Latitude=32.2667&Longitude=71.9167
+1  A: 
str_replace(' ', '&', str_replace(': ', '=', $string));

It may work as you want.

Ionuț G. Stan
+3  A: 

A quick hack

str_replace(array(': ', ' '), array('=', '&'), $string);
Mario
Jayrox
@Jayrox, mine too, but I reckon Mario's solution is better because it has only one function call as opposed to mine which has two.
Ionuț G. Stan
+2  A: 

If, at some point you need to do some validation on your data the str_replace method might stop working for you (although it is the easiest way to solve your problem). You would then want to pull the data out in a smarter but more complicated way:

$string = "Country: USA City: NY Latitude: 32.2667 Longitude: 71.9167";
$matches = Array();
$has_match = preg_match('/Country: (\w+) City: (\w+) Latitude: ([0-9.]+) Longitude: ([0-9.]+)/',$string,$matches);
if ($has_match) {
    list($country,$city,$lat,$long) = array_slice($matches,1);
}
else {
    print "no matches";
}

Now you can do what you like to make sure the $country,$city,$lat and $long values are sane and then join them into a query string with:

$query_string = "Country=$country&City=$city&Latitude=$lat&Longitude=$long"
Freshhawk
its not working out, my string is stored in the variable like that Country: UNITED STATES (US) City: Scottsdale, AZ Latitude: 33.686 Longitude: -111.87
/Country: (.*) City: (.*) Latitude: ([0-9.]+) Longitude: ([0-9.]+)/is a more inclusive regex and should work for your data but is less resiliant to bad data.
Freshhawk
change the regex to: /Country: (\w+) (\(.*\)) City: (\w+),(.*) Latitude: ([0-9.]+) Longitude: ([0-9.]+)/and the match variables to:list($country,$countrycode,$city,$state,$lat,$long) = array_slice($matches, 1);to pull the other information out of it as well.
Freshhawk