parse_str

(PHP 4, PHP 5)

parse_strРазбирает строку в переменные

Описание

void parse_str ( string $str [, array &$arr ] )

Разбирает строку str, которая должна иметь формат строки запроса URL и присваивает значения переменным в текущем контексте.

Замечание:

Для получения текущей QUERY_STRING, можно использовать переменную $_SERVER['QUERY_STRING']. Кроме того, возможно вы захотите прочесть раздел о переменных вне PHP.

Замечание:

Опция magic_quotes_gpc влияет на вывод этой функции, так как parse_str() использует тот же механизм, что используется в PHP для заполнения $_GET, $_POST и других переменных.

Список параметров

str

Входная строка.

arr

Если указан второй параметр arr, то вместо присвоения переменных в текущем контексте они будут сохранены в этом параметре в качестве элементов массива.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Список изменений

Версия Описание
4.0.3 Добавлен параметр arr

Примеры

Пример #1 Использование parse_str()

<?php
$str 
"first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo 
$first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str$output);
echo 
$output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>

Смотрите также

  • parse_url() - Разбирает URL и возвращает его компоненты
  • pathinfo() - Возвращает информацию о пути к файлу
  • http_build_query() - Генерирует URL-кодированную строку запроса
  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc
  • urldecode() - Декодирование URL-кодированной строки

Коментарии

You can perform the opposite of this function if you like with a function like I've built below:

    /**
     * Reverse of parse_str().  Converts array into
     * string with query format
     */
    function query_str ($params) {
        $str = '';
        foreach ($params as $key => $value) {
            $str .= (strlen($str) < 1) ? '' : '&';
            $str .= $key . '=' . rawurlencode($value);
        }
        return ($str);
    }

-- Dante
2003-07-06 01:11:04
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
The documentation does not appear to mention that parse_str also urldecodes each item in the resulting array.

There also appears to be a bug in earlier versions of PHP that causes these urldecoded strings to also be escaped.  (Certainly I was having problems with %22 being turned into /" on my server, but not on my development box, despite forcing magic quotes off).
2004-03-31 13:58:56
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
Note that variables cannot contain a DOT (.) in PHP. So, DOT will be replaced by underscore. 
e.g. variables like "variable.something" will be converted into "variable_something".
2004-06-17 08:23:14
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
If the querystring contains duplicate keys in the key-value pairs, parse_str will only return the last instance of the value.  For example, in the following:

<?php
$mystr 
"test1=blah&test2=bleh&test1=burp";
parse_str($mystr$myarray);
echo 
$myarray['test1'];
?>
The value output will be 'burp'. 

I wrote a function that takes a querystring and returns the the key-value pairs as a two-dimensional array so each duplicate key is available:

<?php
$str 
"test1=blah&test2=bleh&test1=burp";
$valsarray parse_str_ext($str);
echo 
$valsarray['test1'][0];
echo 
$valsarray['test1'][1];
echo 
$valsarray['test2'][0];

function 
parse_str_ext($toparse) {
   
$returnarray = array();
   
$keyvaluepairs split("&"$toparse);
    foreach(
$keyvaluepairs as $pairval) {
       
$splitpair split("="$pairval);
        if(!
array_key_exists($splitpair[0], $returnarray)) $returnarray[$splitpair[0]] = array();

       
$returnarray[$splitpair[0]][] = $splitpair[1];
    }
    return 
$returnarray;   
}
?>

Output will be:
blah
burp
bleh
2004-09-08 23:46:38
http://php5.kiev.ua/manual/ru/function.parse-str.html
I wrote a pair of functions using parse_str() that will write values in an array to a textfile and vice versa, read those values from the textfile back into the array. Quite useful if you need to store lots of data but don't have access to SQL.

Save the array by calling cfg_save($filename,$array) and load it back using $array=cfg_load($filename)

<?php
$newline
="";

function 
cfg_load($cfgfile){
    global 
$newline;
   
$setting="";
    if(
file_exists($cfgfile)){
       
$setting=fopen($cfgfile"r");
       
$ookk="";
        while(
$ook=fgets($setting)){
           
#strip comment
           
$commt=strpos($ook,"##");
            if(
$commt!==false$ook=substr($ook,0,$commt);
           
#append
           
if($ook!=""$ookk=$ookk."&".    str_replace($newline,"\n",str_replace("&","%26",trim($ook)));
        }   
       
fclose($setting);   
       
parse_str($ookk$setting);
    }
    return 
$setting;
}

function 
cfg_save($cfgfile,$setting){
    global 
$intArray;
   
$intArray="";
    for(
$i=0;$i<2000;$i++)
       
$intArray[]=$i;
    if(
is_array($setting)){
       
$allkeys=array_keys($setting);
        foreach(
$allkeys as $aKey)
           
cfg_recurse($setting[$aKey], $aKey$outArray);
    }
   
$cfgf=fopen($cfgfile,"w");
    foreach(
$outArray as $aLine)
       
fputs($cfgf,stripslashes($aLine)."\r\n");
   
fclose($cfgf);
}

function 
cfg_recurse($stuffIn$keysofar, &$toAppend){
    global 
$intArray$newline;
    if(
is_array($stuffIn)){
       
$allkeys=array_keys($stuffIn);
        if(
array_slice($intArray,0,sizeof($allkeys))==$allkeys)
           
$nokey=true;
        else 
           
$nokey=false;
        foreach(
$allkeys as $aKey){
            if(!
$nokey$toKey=$aKey;   
           
cfg_recurse($stuffIn[$aKey], $keysofar."[".$toKey."]"$toAppend);
        }
    }else
       
$toAppend[]=$keysofar."=".str_replace("\n",$newline,$stuffIn);
}
?>

Note that these functions support nested arrays of unlimited levels ;)
2004-10-12 19:10:59
http://php5.kiev.ua/manual/ru/function.parse-str.html
Maybe you need an opposite which works with arrays:

<?php
function query_str ($params) {
    if ( !
is_array($params) || count($params) == ) return false;
   
$fga func_get_args();
   
$akey = ( !isset($fga[1]) ) ? false $fga[1];       
    static 
$out = Array();
   
    foreach ( 
$params as $key=>$val ) {
        if ( 
is_array($val) ) {   
           
query_str($val,$key);
            continue;
        }

       
$thekey = ( !$akey ) ? $key $akey.'['.$key.']';
       
$out[] = $thekey."=".$val;
    }
   
    return 
implode("&",$out);   
}
?>
2005-02-03 04:29:55
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
yet another simpler way to do the reverse this function.
<?php
   
/* BSD LINCENSE */
   
function build_str($query_array) {
       
$query_string = array();
        foreach (
$query_array as $k => $v) {
           
$query_string[] = $k.'='.$v;
        }
        return 
join('&'$query_string);
    }

   
// example of use
    // set  a query string
   
$test_query "a=b&c=d";
   
// parse a string
   
parse_str($test_query$query_array);
   
//print it
   
print_r($query_array);
   
   
// test the build_str function
   
if ( build_str($query_array) == $test_query ) {
        echo 
"It works";
    } else {
        echo 
"It doesn't work";
    }

?>
2005-03-10 18:26:51
http://php5.kiev.ua/manual/ru/function.parse-str.html
You may want to parse the query string into an array. 

<?php
/**
 * Similar to parse_str. Returns false if the query string or URL is empty. Because we're not parsing to 
 * variables but to array key entries, this function will handle ?[]=1&[]=2 "correctly."
 *
 * @return array Similar to the $_GET formatting that PHP does automagically.
 * @param string $url A query string or URL 
 * @param boolean $qmark Find and strip out everything before the question mark in the string
*/
function parse_query_string($url$qmark=true)
{
    if (
$qmark) {
       
$pos strpos($url"?");
        if (
$pos !== false) {
           
$url substr($url$pos 1);
        }
    }
    if (empty(
$url))
        return 
false;
   
$tokens explode("&"$url);
   
$urlVars = array();
    foreach (
$tokens as $token) {
       
$value string_pair($token"=""");
        if (
preg_match('/^([^\[]*)(\[.*\])$/'$token$matches)) {
           
parse_query_string_array($urlVars$matches[1], $matches[2], $value);
        } else {
           
$urlVars[urldecode($token)] = urldecode($value);
        }
    }
    return 
$urlVars;
}

/**
 * Utility function for parse_query_string. Given a result array, a starting key, and a set of keys formatted like "[a][b][c]" 
 * and the final value, updates the result array with the correct PHP array keys.
 *
 * @return void
 * @param array $result A result array to populate from the query string
 * @param string $k The starting key to populate in $result
 * @param string $arrayKeys The key list to parse in the form "[][a][what%20ever]"
 * @param string $value The value to place at the destination array key
*/
function parse_query_string_array(&$result$k$arrayKeys$value)
{
    if (!
preg_match_all('/\[([^\]]*)\]/'$arrayKeys$matches))
        return 
$value;
    if (!isset(
$result[$k])) {
       
$result[urldecode($k)] = array();
    }
   
$temp =& $result[$k];
   
$last urldecode(array_pop($matches[1]));
    foreach (
$matches[1] as $k) {
       
$k urldecode($k);
        if (
$k === "") {
           
$temp[] = array();
           
$temp =& $temp[count($temp)-1];
        } else if (!isset(
$temp[$k])) {
           
$temp[$k] = array();
           
$temp =& $temp[$k];
        }
    }
    if (
$last === "") {
       
$temp[] = $value;
    } else {
       
$temp[urldecode($last)] = $value;
    }
}

/**
* Breaks a string into a pair for a common parsing function. 
*
* The string passed in is truncated to the left half of the string pair, if any, and the right half, if anything, is returned.
*
* An example of using this would be:
* <code>
* $path = "Account.Balance";
* $field = string_pair($path);

* $path is "Account"
* $field is "Balance"
*
* $path = "Account";
* $field = string_pair($path);
*
* $path is "Account"
* $field is false
* </code>
*
* @return string The "right" portion of the string is returned if the delimiter is found.
* @param string $a A string to break into a pair. The "left" portion of the string is returned here if the delimiter is found.
* @param string $delim The characters used to delimit a string pair
* @param mixed $default The value to return if the delimiter is not found in the string
* @desc 
*/
function string_pair(&$a$delim='.'$default=false)
{
   
$n strpos($a$delim);
    if (
$n === false)
        return 
$default;
   
$result substr($a$n+strlen($delim));
   
$a substr($a0$n);
    return 
$result;
}

?>
2005-05-06 11:13:13
http://php5.kiev.ua/manual/ru/function.parse-str.html
In Kent's solution you may wish to switch "urldecode" into "rawurldecode" if you'd like to get rid of the [annoying] plus '+' converted to space ' ' translation.
2005-05-25 03:18:15
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
This does not work as expected.

<?php
class someclass
{
    var 
$query_string;
    function 
someclass($a_query_string)
    {
       
$this->query_string $a_query_string;
       
parse_str($this->query_string);
    }
    function 
output()
    {
        echo 
$this->action;
    }
}

$a_class = new someclass("action=go");
$a_class->output();
?>

Use this instead.

<?php
class someclass
{
    var 
$arr;
    function 
someclass($a_query_string)
    {
       
parse_str($a_query_string$this->arr);
    }
    function 
output()
    {
        echo 
$this->arr['action'];
    }
}

$a_class = new someclass("action=go");
$a_class->output();
?>
2005-05-29 12:22:43
http://php5.kiev.ua/manual/ru/function.parse-str.html
this can be another option for STR PARSING and use it as a $_GET variable.
<?php 
$str
"op=downloads&id=1&details=1";
function 
parse_to_get($str=false){
    if(
$REQUEST_URI==$str): $ex explode("/".$PHP_SELF."?"$str); $str $ex[1]; endif;
    if(
$str):
       
$a explode("&"$str);
        foreach(
$a as $e){
            if(
$e):
                list(
$k,$v)=explode("="$e);
               
$_GET[$k]=$v;
            endif;
        }
    endif;
   
extract($_GET);
}
parse_top_get("index.php?page=info&name=jonh&id=4245&app=server");

?>
:)

//Trukin
2005-06-20 02:46:14
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
As of PHP 5, you can do the exact opposite with http_build_query(). Just remember to use the optional array output parameter.

This is a very useful combination if you want to re-use a search string url, but also slightly modify it:

Example:
<?
$url1 
"action=search&interest[]=sports&interest[]=music&sort=id";
$str parse_str($url1$output);

// Modifying criteria:
$output['sort'] = "interest";

$url2 http_build_query($output);

echo 
"<br>url1: ".$url1;
echo 
"<br>url2: ".$url2;
?>

Results in:
url1: action=search&interest[]=sports&interest[]=music&sort=id
url2: action=search&interest[0]=sports&interest[1]=music&sort=interest

(Array indexes are automatically created.)
2005-06-29 08:59:20
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
In reply to what kerosuppi posted:

[quote]This does not work as expected.[/quote]
No, it works exactly as expected.

The call <?php parse_str($this->query_string);?>  "sets variables in the current scope" (just like said in the manual).

You are using this call in the constructor. Once the constructor is finished, the scope of this function has ended so it's logical that you can't access the variables anymore.

Your workaround though is a good one.

Hope this helps,
ET
2005-09-01 06:14:48
http://php5.kiev.ua/manual/ru/function.parse-str.html
If you are trying to preserve a complex array, the function serialize might be better than http_build_query or other methods of making a query string.
2005-09-03 21:32:26
http://php5.kiev.ua/manual/ru/function.parse-str.html
When you have scripts run through the command-line (like locally via cron), you might want to be able to use _GET and _POST vars. Put this in top of your scheduled task files:

<?
    parse_str 
($_SERVER['argv'][1], $GLOBALS['_GET']);
   
parse_str ($_SERVER['argv'][2], $GLOBALS['_POST']);
?>

And call your script by:

/usr/local/bin/php /path/to/script.php "id=45&action=delete" "formsubmitted=true"

Cheers!
2006-04-14 21:13:13
http://php5.kiev.ua/manual/ru/function.parse-str.html
CONVERT ANY FORMATTED STRING INTO VARIABLES

I developed a online payment solution for credit cards using a merchant, and this merchant returns me an answer of the state of the transaction like this:

estado=1,txnid=5555444-8454445-4455554,monto=100.00

to have all that data into variables could be fine for me! so i use str_replace(), the problem is this function recognizes each group of variables with the & character... and i have  comma separated values... so i replace comma with &

<?php
$string 
"estado=1,txnid=5555444-8454445-4455554,monto=100.00";
$string str_replace(",","&",$string);
parse_str($string);
echo 
$monto// outputs 100.00
?>
2006-08-28 21:21:12
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
This function is confused by ampersands (&) being encoded as HTML entities (&amp;).

$str = "first=value&amp;arr[]=foo+bar&amp;arr[]=baz";
parse_str($str, $output);
print_r($output);

Array
(
    [first] => value
    [amp;arr] => Array
        (
            [0] => foo bar
            [1] => baz
        )
)
2006-09-08 17:15:40
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
Vladimir: the function is OK in how it deals with &amp;.
&amp; must only be used when outputing URLs in HTML/XML data.
You should ask yourself why you have &amp; in your URL when you give it to parse_str.
2006-10-07 17:02:09
http://php5.kiev.ua/manual/ru/function.parse-str.html
Vladimir Kornea wrote on 8 Sep 2006:
"This function is confused by ampersands (&) being encoded as HTML entities (&amp;)"

Well, it would be - it's not supposed to be passed html entities, that's a different encoding scheme. This function does correctly decode url encoded params for you though (with the rawurlencode rather than urlencode, ie '+' is translated to a space).
2007-01-31 06:52:47
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
if you would like to get a nice url scheme with php/apache and and want to handle all requests in a central php script there's a simple solution/hack:

create a .htaccess in your "basedir" where you've got your main script (in this example index.php) containing some lines like:

"ErrorDocument 404 /index.php"

inside index.php you can now do

<?php
    $virtual_path 
substr(
       
$_SERVER['REQUEST_URI'],
       
strlendirname$_SERVER['PHP_SELF'] ) ) + 1
   
);
    if( (
$pos strpos$virtual_path'?' )) !== false ) {
       
parse_strsubstr$virtual_path$pos ), $_GET );
       
$_REQUEST array_merge$_REQUEST$_GET );
       
$virtual_path substr$virtual_path0$pos );
    }

   
// some code checking for a valid location, etc...
   
header'HTTP/1.1 200 OK' );
   
header'Content-Type: text/plain' );

    echo 
$virtual_path."\n\n";
   
print_r$_REQUEST );
?>

// guido 'lenix' boehm
2007-02-10 18:20:34
http://php5.kiev.ua/manual/ru/function.parse-str.html
This is probably a better solution than below. The first line makes sure the file doesn't exist then the second line directs all requests to a script. No need to output a 200 header with this method either.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php      [L]
2007-03-07 14:32:10
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
Vladimir Kornea:
Try use html_entity_decode()

$str = 'first=value&amp;arr[]=foo+bar&amp;arr[]=baz';
parse_str(html_entity_decode($str), $output);
print_r($output);

Array
(
    [first] => value
    [arr] => Array
        (
            [0] => foo bar
            [1] => baz
        )

)
2007-04-28 14:27:45
http://php5.kiev.ua/manual/ru/function.parse-str.html
Here is a little function that does the opposite of the parse_str function. It will take an array and build a query string from it.

<?php

/* Converts an array of parameters into a query string to be appended to a URL.
 *
 * @return  string              : Query string to append to a URL.
 * @param   array    $array     : Array of parameters to append to the query string.
 * @param   string   $parent    : This should be left blank (it is used internally by the function).
 */
function append_params($array$parent='')
{
   
$params = array();
    foreach (
$array as $k => $v)
    {
        if (
is_array($v))
           
$params[] = append_params($v, (empty($parent) ? urlencode($k) : $parent '[' urlencode($k) . ']'));
        else
           
$params[] = (!empty($parent) ? $parent '[' urlencode($k) . ']' urlencode($k)) . '=' urlencode($v);
    }

   
$sessid session_id();
    if (!empty(
$parent) || empty($sessid))
        return 
implode('&'$params);

   
// Append the session ID to the query string if we have to.
   
$sessname session_name();
    if (
ini_get('session.use_cookies'))
    {
        if (!
ini_get('session.use_only_cookies') && (!isset($_COOKIE[$sessname]) || ($_COOKIE[$sessname] != $sessid)))
           
$params[] = $sessname '=' urlencode($sessid);
    }
    elseif (!
ini_get('session.use_only_cookies'))
       
$params[] = $sessname '=' urlencode($sessid);

    return 
implode('&'$params);
}

?>

Note that the function will also append the session ID to the query string if it needs to be.
2007-06-02 15:25:01
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
parse_str() contained a bug (#39763) in PHP 5.2.0 that caused it to apply magic quotes twice. This bug was marked as fixed in the release notes of PHP 5.2.1, but there were apparently some issues with getting the fix through CVS on time, as our install of PHP 5.2.1 was still affected by it.
2007-07-17 11:46:21
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
parse_str() is confused by ampersands (&) being encoded as HTML entities (&amp;). This is relevant if you're extracting your query string from an HTML page (scraping). The solution is to run the string through html_entity_decode() before running it through parse_str().

(Editors: my original comment was a caution whose solution is obvious, but it has resulted in three replies ("so what?" "as intended" and "this is how to fix it"). Please remove the previous four posts dealing with this (69529, 70234, 72745, 74818) and leave just the above summary. This issue is too trivial to warrant the number of comments it has received.)
2007-07-17 12:04:52
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields.  If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:

<?php
# silently fails to handle multiple values
parse_str('foo=1&foo=2&foo=3');

# the above produces:
$foo = array('foo' => '3');
?>

Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.

<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=3');

# the above produces:
$foo = array('foo' => array('1''2''3') );
?>

This can be confusing for anyone who's used to the CGI standard, so keep it in mind.  As an alternative, I use a "proper" querystring parser function:

<?php
function proper_parse_str($str) {
 
# result array
 
$arr = array();

 
# split on outer delimiter
 
$pairs explode('&'$str);

 
# loop through each pair
 
foreach ($pairs as $i) {
   
# split into name and value
   
list($name,$value) = explode('='$i2);
   
   
# if name already exists
   
if( isset($arr[$name]) ) {
     
# stick multiple values into an array
     
if( is_array($arr[$name]) ) {
       
$arr[$name][] = $value;
      }
      else {
       
$arr[$name] = array($arr[$name], $value);
      }
    }
   
# otherwise, simply stick it in a scalar
   
else {
     
$arr[$name] = $value;
    }
  }

 
# return result array
 
return $arr;
}

$query proper_parse_str($_SERVER['QUERY_STRING']);
?>
2007-07-30 22:43:56
http://php5.kiev.ua/manual/ru/function.parse-str.html
An old post from several years ago mentions that variable names cannot have a dot. They also cannot have a space. Spaces are automatically replaced with an underscore.

The following:
parse_str("My Value=Something", $result);

Will result in:
$result['My_Value'] = 'Something'

Although I understand why it is done, I still feel that this is unintuitive behavior.
2007-08-08 14:09:41
http://php5.kiev.ua/manual/ru/function.parse-str.html
I saw some posts with people wondering
 why &'s are being
 sent to this function.  Well, basically
 because thats what comes
 from a QUERY_STRING. Anyway. The bug i found is
 that the first part of a query_string
 may not contain an &. Usually the
 first parameter comes directly after the ?. 
So you
 might have to manually pre-pend an & to your
 query_string if one does not exist. 

<?php
$base
="www.yahoo.com/search.aspx?";
$parsedurl=parse_url($base."&".rawurldecode($_SERVER
['QUERY_STRING']), PHP_URL_QUERY);
parse_str($parsedurl,$myquery);
$qbn "n=".urlencode($myquery['n']);
?>

oh my god! to get this to post is ridiculous.
2007-08-30 15:51:39
http://php5.kiev.ua/manual/ru/function.parse-str.html
If you wish a version of parse_str sans magic quotes, the following will do the trick:

<?php
function parse_query($str) {
   
$pairs explode('&'$str);

    foreach(
$pairs as $pair) {
        list(
$name$value) = explode('='$pair2);
        global $
$name;
        $
$name $value;
    }
}
?>
2007-10-31 10:48:58
http://php5.kiev.ua/manual/ru/function.parse-str.html
I shouldn't've posted the original version, as it only worked with the most basic of query strings.

This function will parse an html-safe query-like url string for variables and php-like ordered and associative arrays.  It places them into the global scope as parse_str does and adds minimal slashes for database insertions without the triple-slash problems that magic quotes can produce (the reason I had to write it in the first place).  If you don't need the slashes, they're easy enough to remove.

<?php
function parse_query($str) {
   
   
// Separate all name-value pairs
   
$pairs explode('&'$str);
   
    foreach(
$pairs as $pair) {
       
       
// Pull out the names and the values
       
list($name$value) = explode('='$pair2);
       
       
// Decode the variable name and look for arrays
       
list($name$index) = split('[][]'urldecode($name));
       
       
// Arrays
       
if(isset($index)) {
           
           
// Declare or add to the global array defined by $name
           
global $$name;
            if(!isset($
$name)) $$name = array();
           
           
// Associative array
           
if($index != "") {
                ${
$name}[$index] = addslashes(urldecode($value));
               
           
// Ordered array
           
} else {
               
array_push($$nameaddslashes(urldecode($value)));
            }
       
       
// Variables
       
} else {
           
           
// Declare or overwrite the global variable defined by $name
           
global $$name;
            $
$name addslashes(urldecode($value));
        }
    }
}
?>
2007-11-13 18:02:59
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
Be careful when use the second parameter, this function cleans array var first. Look this:

<?php
$vars
["foo"] = "foovalue";
$queryString "bar=barvalue&stuff=stuffval";
parse_str($queryString$vars);
echo 
"<pre>";
print_r($vars);
echo 
"</pre>";
?> 

Result:

Array
(
    [bar] => barvalue
    [stuff] => stuffval
)

it is solved by:

<?php
$prevVars
["foo"] = "foovalue";
$queryString "bar=barvalue&stuff=stuffval";
$newVars = array();
parse_str($queryString$newVars);

$vars array_merge($prevVars$newVars);
echo 
"<pre>";
print_r($vars);
echo 
"</pre>";
?>

Result:

Array
(
    [foo] => foovalue
    [bar] => barvalue
    [stuff] => stuffval
)
2008-03-28 10:44:47
http://php5.kiev.ua/manual/ru/function.parse-str.html
This function automatically urldecodes values (not mentioned in the docs).
2008-04-21 12:39:38
http://php5.kiev.ua/manual/ru/function.parse-str.html
<? 
//by shimon doodkin

 
$url_form=url_to_form($url);
 echo 
'<form action="'.$url_form['action'].'" method="get">';
 echo 
$url_form['hidden'];
 echo 
'<input name="otherfiled" type="text">';
 echo 
'<input type="submit">';
 echo 
'</form>';

 function 
url_to_form($url)
 {
 
$url=split('\?',$url,2);
 
$action=$url[0];
 
$hidden="";
  if(isset(
$url[1]))
  {
   
$pairs=split('&',$url[1]);
   foreach(
$pairs as $pair)
   {
   
$pair=split('=',$pair,2);
   
$name=$pair[0];
    if(isset(
$pair[1]))
     
$value=$pair[1];
    else
     
$value='';
   
$name=$name;
   
$value=htmlspecialchars($value);
    if(
$name!='')
     
$hidden.='<hidden name="'.$name.'" value="'.$value.'">';
   }
  }
  return array(
'action'=>$action,'hidden'=>$hidden);
 }

?>
2008-04-28 12:09:34
http://php5.kiev.ua/manual/ru/function.parse-str.html
just a heads up with the example above:
?var[]=123 - the [] has to be urlencoded.
var names and var values - both have to be urlencoded!
2008-07-01 14:17:18
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
In addition to Maikel's posting, the following will iterate through previous arrays and automatically apply them to the current array.

The following code was implemented for YUI's Cookie/subCookie utility in which all form elements were stored as subcookies. This parses cookies and stores all cookie params (minus the parent value) into $_POST variables. if you would like to put elements into array's of the parent, just use the commented out line instead of the if statement.

<?php
// thise parses cookies and stores all fields as variables
foreach ($_COOKIE as $key => $value) {
   
// parse_str overwrites previous array values so we must merge the previous ones with new array
   
if (isset($_POST)) {
       
$_POST_old $_POST;
       
parse_str($value$_POST);
       
$_POST array_merge($_POST_old$_POST);
    }
   
// this puts all elements as children of parent array
    // comment out above if statement to use this instead
    //parse_str($key, $_POST[$value]);
}
echo 
"<pre>";
print_r($_POST);
echo 
"</pre>";
?>
2008-07-23 09:40:13
http://php5.kiev.ua/manual/ru/function.parse-str.html
Also, an FYI but you cannot define arr when you call the function. I.E

<?php
$string
="Tom=You&Zach=Me";
parse_str($string,$array);
print_r($array);
// Undefined variable $array on line 2!!!!
?>

However, if you define the array before hand, it works.

<?php
$string
="Tom=You&Zach=Me";
$array=array();
parse_str($string,$array);
print_r($array);
/*
Array
(
  [Tom] => You
  [Zach] => Me
)
*/
?>
2009-03-13 13:08:54
http://php5.kiev.ua/manual/ru/function.parse-str.html
Hi, 
I discovered that

<?php
$query 
'foo.bar=stuff';    // foo (dot) bar
parse_str$query $output);
print_r$output );
?>

will output (underscore)

Array
(
    [foo_bar] => stuff
)

and not as expected (dot)

Array
(
    [foo.bar] => stuff
)

Query part of a requested URI is parsed the same. So never send parameters with a dot in their names

Hope it will save you time, 
bye julien
2009-06-22 04:53:10
http://php5.kiev.ua/manual/ru/function.parse-str.html
be careful using parse_str() without the [array &$arr] parameter, as this may override values of global and existing variables.

<?php
$var1 
1;
parse_str('var1=one&var2=two');
// $var1 is now 'one'
?>

Also may lead to variable value injection when used with user input data:

<?php
$_POST
['range'] = 'min=1&max=5&important_var=important_value_no_more';

$important_var 'important_value';
parse_str($_POST['range']);
?>
2010-02-04 04:48:00
http://php5.kiev.ua/manual/ru/function.parse-str.html
If you're using .htaccess to spoof pages in any type of application, then $QUERY_STRING or $_SERVER['QUERY_STRING'] is going to be blank.  Instead, $_SERVER['REDIRECT_QUERY_STRING'] will hold the actual query string passed by user.  Use this function to parse this variable.
2010-06-29 04:28:12
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
If you need a function that does something similar to parse_str, but doesn't convert spaces and dots to underscores, try something like the following:

<?php
function parseQueryString($str) {
   
$op = array();
   
$pairs explode("&"$str);
    foreach (
$pairs as $pair) {
        list(
$k$v) = array_map("urldecode"explode("="$pair));
       
$op[$k] = $v;
    }
    return 
$op;
}
?>

It may need adapting to handle various edge cases.
2010-08-12 14:07:50
http://php5.kiev.ua/manual/ru/function.parse-str.html
I wrote an array to string function that works recursively and works with an n-dimensional array turning it into a parsable string for parse_str. 

<?php
function queryString($params$name=null) {
$ret "";
 foreach(
$params as $key=>$val) {
  if(
is_array($val)) {
   if(
$name==null$ret .= queryString($val$key);
   else 
$ret .= queryString($val$name."[$key]");   
   } else {
   if(
$name!=null)
   
$ret.=$name."[$key]"."=$val&";
   else 
$ret.= "$key=$val&";
  }
 }
 return 
$ret;   
}
?>
2011-02-02 18:54:02
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
function like parse_str, but doesn't convert spaces and dots to underscores in $_GET AND $_POST

/**
 * GET and POST input containing dots, etc.
 */
function getRealREQUEST() {
    $vars = array();

    $input    = $_SERVER['REDIRECT_QUERY_STRING'];
    if(!empty($input)){
        $pairs    = explode("&", $input);
        foreach ($pairs     as $pair) {
            $nv                = explode("=", $pair);
           
            $name            = urldecode($nv[0]);
            $nameSanitize    = preg_replace('/([^\[]*)\[.*$/','$1',$name);
           
            $nameMatched    = str_replace('.','_',$nameSanitize);
            $nameMatched    = str_replace(' ','_',$nameMatched);
           
            $vars[$nameSanitize]    = $_REQUEST[$nameMatched];
        }
    }
   
    $input    = file_get_contents("php://input");
    if(!empty($input)){
        $pairs    = explode("&", $input);
        foreach ($pairs as $pair) {
            $nv                = explode("=", $pair);
           
            $name            = urldecode($nv[0]);
            $nameSanitize    = preg_replace('/([^\[]*)\[.*$/','$1',$name);
           
            $nameMatched    = str_replace('.','_',$nameSanitize);
            $nameMatched    = str_replace(' ','_',$nameMatched);
           
            $vars[$nameSanitize]    = $_REQUEST[$nameMatched];
        }
    }
   
    return $vars;
}
2012-04-26 12:18:11
http://php5.kiev.ua/manual/ru/function.parse-str.html
Автор:
That's not says in the description but max_input_vars directive affects this function. If there are more input variables on the string than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.
2012-05-14 08:51:27
http://php5.kiev.ua/manual/ru/function.parse-str.html

    Поддержать сайт на родительском проекте КГБ