1

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

4

7 回答 7

8

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.

于 2009-02-25T21:19:18.100 回答
3
$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.

于 2009-02-25T21:23:42.737 回答
2

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'];
于 2009-02-25T21:28:35.270 回答
0

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.

于 2009-02-25T21:19:44.433 回答
0

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.

于 2009-02-25T21:21:55.723 回答
0

All of the other Answers are Insufficient. This Should Work Every Time!

function slice($string, $start){
  $st = $string; $s = $start; $l = strlen($st); $a = func_get_args();
  $e = isset($a[2]) ? $a[2] : $l;
  $f = $e-$s;
  $p = $e < 0 && $s > 0 ? $l+$f : $f;
  return substr($st, $s, $p);
}
于 2013-06-14T02:22:49.760 回答
-1

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

于 2009-02-25T21:15:55.877 回答