Reputation: 757
I have a text string that looks like this
var1=red&var2=green&var3=blue&var4=magenta
How can manipulate this string isolate the value of var2
which in this case is green
Upvotes: 3
Views: 65
Reputation: 2477
I'd start with parse_url What you have looks close enough to an URL param string that you might as well use the built in methods for handling URLs.
Upvotes: 3
Reputation: 43619
You can use parse_str
function to parse the string into an array / variables. In this case I prefer outputting to array instead of variables to prevent the pollution of namespace.
<?php
$str = 'var1=red&var2=green&var3=blue&var4=magenta';
parse_str($str, $output);
$result = null;
foreach($output as $k => $v){
if($v == 'green'){
$result = $k;
break;
}
}
?>
Upvotes: 1
Reputation: 324840
Try this:
parse_str($str,$tmp);
// $tmp['var2'] is now what you're looking for
Upvotes: 3