Question
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
Solution
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.
OTHER TIPS
$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.
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'];
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.
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.
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);
}
I suggest you read about regular expressions in the PHP help.