samquo
samquo

Reputation: 757

processing this string with php

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

Answers (5)

speshak
speshak

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

IamSimon
IamSimon

Reputation: 71

Use the php function parse_str() to convert it to an array.

Upvotes: 7

mauris
mauris

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

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

Try this:

parse_str($str,$tmp);
// $tmp['var2'] is now what you're looking for

Upvotes: 3

deceze
deceze

Reputation: 522625

parse_str($str, $vars);
echo $vars['var2'];

Upvotes: 3

Related Questions