3

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

5 Answers 5

7

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

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

Comments

3

Try this:

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

Comments

1

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;
    }
}

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.