processing this string with php
I have a text string that looks like this
var1=red&var2=g开发者_StackOverflow社区reen&var3=blue&var4=magenta
How can manipulate this string isolate the value of var2
which in this case is green
Use the php function parse_str() to convert it to an array.
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.
parse_str($str, $vars);
echo $vars['var2'];
Try this:
parse_str($str,$tmp);
// $tmp['var2'] is now what you're looking for
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;
}
}
?>
精彩评论