0

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
2
  • What you describe isn't really parsing but rather string manipulation. Parsing entails extracting structured data from a string. Commented Feb 25, 2009 at 17:20
  • It's structured data. It just happens that a quick str replace hack is possible. Commented Feb 25, 2009 at 17:38

4 Answers 4

3

A quick hack

str_replace(array(': ', ' '), array('=', '&'), $string);
Sign up to request clarification or add additional context in comments.

2 Comments

i like this one better because it takes care of ': ' before ' ' which prevents ':&'
@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.
2
str_replace(' ', '&', str_replace(': ', '=', $string));

It may work as you want.

Comments

2

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"

3 Comments

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.
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.
0

The regular expresion in the second answer is ok but it need some small corrections.

preg_match('/^Country=(\w+)&City=(\w+)&Latitude=([0-9.]+)&Longitude=([0-9.]+)/',$string,$matches);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.