parse_str
Parses string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).
Parameters
If the second parameter result is present, variables are stored in this variable as array elements instead.
Using this function without the result parameter is highly DISCOURAGED and DEPRECATED as of PHP 7.2. As of PHP 8.0.0, the result parameter is mandatory.
Return Values
Changelog
Version | Description |
---|---|
8.0.0 | result is no longer optional. |
7.2.0 | Usage of parse_str() without a second parameter now emits an E_DEPRECATED notice. |
Examples
Example #1 Using parse_str()
// Recommended
parse_str ( $str , $output );
echo $output [ ‘first’ ]; // value
echo $output [ ‘arr’ ][ 0 ]; // foo bar
echo $output [ ‘arr’ ][ 1 ]; // baz
// DISCOURAGED
parse_str ( $str );
echo $first ; // value
echo $arr [ 0 ]; // foo bar
echo $arr [ 1 ]; // baz
?>
Because variables in PHP can’t have dots and spaces in their names, those are converted to underscores. Same applies to naming of respective key names in case of using this function with result parameter.
Example #2 parse_str() name mangling
parse_str ( «My Value=Something» );
echo $My_Value ; // Something
?php
parse_str ( «My Value=Something» , $output );
echo $output [ ‘My_Value’ ]; // Something
?>
Notes
Note:
All variables created (or values returned into array if second parameter is set) are already urldecode() d.
Note:
To get the current QUERY_STRING , you may use the variable $_SERVER[‘QUERY_STRING’] . Also, you may want to read the section on variables from external sources.
See Also
- parse_url() — Parse a URL and return its components
- pathinfo() — Returns information about a file path
- http_build_query() — Generate URL-encoded query string
- urldecode() — Decodes URL-encoded string
User Contributed Notes 32 notes
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:
# 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.
# 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:
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 ( ‘=’ , $i , 2 );
# 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’ ]);
?>
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.
if you need custom arg separator, you can use this function. it returns parsed query as associative array.
/**
* Parses http query string into an array
*
* @author Alxcube
*
* @param string $queryString String to parse
* @param string $argSeparator Query arguments separator
* @param integer $decType Decoding type
* @return array
*/
function http_parse_query ( $queryString , $argSeparator = ‘&’ , $decType = PHP_QUERY_RFC1738 ) $result = array();
$parts = explode ( $argSeparator , $queryString );
foreach ( $parts as $part ) list( $paramName , $paramValue ) = explode ( ‘=’ , $part , 2 );
switch ( $decType ) case PHP_QUERY_RFC3986 :
$paramName = rawurldecode ( $paramName );
$paramValue = rawurldecode ( $paramValue );
break;
case PHP_QUERY_RFC1738 :
default:
$paramName = urldecode ( $paramName );
$paramValue = urldecode ( $paramValue );
break;
>
if ( preg_match_all ( ‘/\[([^\]]*)\]/m’ , $paramName , $matches )) $paramName = substr ( $paramName , 0 , strpos ( $paramName , ‘[‘ ));
$keys = array_merge (array( $paramName ), $matches [ 1 ]);
> else $keys = array( $paramName );
>
foreach ( $keys as $index ) if ( $index === » ) if (isset( $target )) if ( is_array ( $target )) $intKeys = array_filter ( array_keys ( $target ), ‘is_int’ );
$index = count ( $intKeys ) ? max ( $intKeys )+ 1 : 0 ;
> else $target = array( $target );
$index = 1 ;
>
> else $target = array();
$index = 0 ;
>
> elseif (isset( $target [ $index ]) && ! is_array ( $target [ $index ])) $target [ $index ] = array( $target [ $index ]);
>
if ( is_array ( $target )) $target [] = $paramValue ;
> else $target = $paramValue ;
>
>
Vladimir: the function is OK in how it deals with &.
& must only be used when outputing URLs in HTML/XML data.
You should ask yourself why you have & in your URL when you give it to parse_str.
You may want to parse the query string into an array.
/**
* 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 , » keyword»>, «» );
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:
*
* $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
*
*
* @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 ( $a , 0 , $n );
return $result ;
>
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:
// Modifying criteria:
$output[‘sort’] = «interest»;
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.)
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!
parse_str
Разбирает строку str , которая должна иметь формат строки запроса URL и присваивает значения переменным в текущем контексте.
Замечание:
Для получения текущей QUERY_STRING, можно использовать переменную $_SERVER[‘QUERY_STRING’] . Кроме того, возможно вы захотите прочесть раздел о переменных вне PHP.
Замечание:
Опция magic_quotes_gpc влияет на вывод этой функции, так как parse_str() использует тот же механизм, что используется в PHP для заполнения $_GET , $_POST и других переменных.
Список параметров
Если указан второй параметр arr , то вместо присвоения переменных в текущем контексте они будут сохранены в этом параметре в качестве элементов массива.
Возвращаемые значения
Эта функция не возвращает значения после выполнения.
Примеры
Пример #1 Использование parse_str()
$str = «first=value&arr[]=foo+bar&arr[]=baz» ;
parse_str ( $str );
echo $first ; // value
echo $arr [ 0 ]; // foo bar
echo $arr [ 1 ]; // baz
?php
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() — Получение текущего значения настройки конфигурации magic_quotes_gpc
- urldecode() — Декодирование URL-кодированной строки