views:

478

answers:

6

is there a way to slice a string lets say i have this variable

$output=Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87

i want to slice it in a way i want to pull latitude and longitude values in to seperate variables, subtok is not serving the purpose

A: 

I suggest you read about regular expressions in the PHP help.

Assaf Lavie
+8  A: 

You don't need a regular expression for this; use explode() to split up the string, first by &, and then by =, which you can use to effectively parse it into a nice little array mapping names to values.

Rob
A: 

I'm not sure exactly what you're demonstrating in your code, maybe it's just some typos, is the "$output" the name of the variable, or part of the string?

Assuming it's the name of the variable, and you just forgot to put the quotes on the string, you have a couple options:


$sliced = explode('&', $output)

This will create an array with values: "Country=UNITED STATES(US) ", "City=Scottsdale, AZ ", etc.


$sliced = preg_split('/[&=]/', $output);

This will create an array with alternating elements being the "variables" and their values: "Country", "UNITED STATES(US) ", "City", "Scottsdale, AZ ", etc.

Chad Birch
A: 

You could do the following:

$output = 'Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87';

$strs = explode('&', $output);
foreach ($strs as $str) {

   list($var, $val) = explode('=',$str);
   $$var = trim($val);

}

This would give you variables such as $Latitude and $Longitude that are set to the value in the key/value pair.

jonstjohn
Variable variables? Please no :(
Alex Fort
This is a really bad idea. What if your keys contain spaces? PHP's associative arrays make more sense here:$array[$var] = trim($val);
eplawless
+1  A: 
$output='Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87';
parse_str($output, $array);
$latitude = $array['latitude'];

You could also just do

parse_str($output);
echo $latitude;

I think using an array is better as you are not creating variables all over the place, which could potentially be dangerous (like register_globals) if you don't trust the input string.

Tom Haigh
+1  A: 

It looks likes it's coming from an URL, although the URL encoding is gone.

I second the suggestions of using explode() or preg_split() but you might also be interested in parse_str().

$output = "City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87";
parse_str($output, $results);
$lat = $results['Latitude'];
$lon = $results['Longitude'];
lpfavreau