I've got a this text
"?foo=bar&foobar=barfoo"
what is the best way to convert this text to variable? Like this:
<?php
echo $q['foo']; //bar
echo $q['foobar']; //barfoo
?>
Thanks.
Sorry for my English.
I've got a this text
"?foo=bar&foobar=barfoo"
what is the best way to convert this text to variable? Like this:
<?php
echo $q['foo']; //bar
echo $q['foobar']; //barfoo
?>
Thanks.
Sorry for my English.
see http://docs.php.net/parse_str and http://docs.php.net/parse_url
$s = "?foo=bar&foobar=barfoo";
parse_str(parse_url($s, PHP_URL_QUERY), $q);
var_dump($q);
prints
array(2) {
["foo"]=>
string(3) "bar"
["foobar"]=>
string(6) "barfoo"
}
edit: If you know the string always has the form ?x=y... you might want to skip parse_url() and use substr() instead.
edit2: Keep in mind that the behavior of parse_str() depends on the value of arg_separator.input. Should you set it (for whatever reason) to something like '!' parse_string() will return NULL for your input string.
e.g.
ini_set('arg_separator.input', '!');
$s = "foo=bar&foobar=barfoo";
var_dump(parse_str($s));
prints NULL
. But ...that would be a rather odd setting.
Well this is a url so if you get it from a url source they should be automatically in $_GET['foo'] and $_GET['bar'] but if it's just a text string, you can do this:
$string = "?foo=bar&foobar=barfoo";
$string = str_replace('?', '', $string);
$params = explode('&', $string);
foreach($params as $key=>$value)
{
$data = explode('=', $value);
$_GET[$data[0]] = $data[1];
}
And all of your vars will be in $_GET array.