Professional Documents
Culture Documents
PHP - Parse - STR - Manual
PHP - Parse - STR - Manual
Downloads
Documentation
Get Involved
Help
Search
PHP Conference China 2020
Getting Started
Introduction
A simple tutorial
Language Reference
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects
Namespaces
Errors
Exceptions
Generators
References Explained
Predefined Variables
Predefined Exceptions
Predefined Interfaces and Classes
Context options and parameters
Supported Protocols and Wrappers
Security
Introduction
General considerations
Installed as CGI binary
Installed as an Apache module
Session Security
Filesystem Security
Database Security
Error Reporting
Using Register Globals
User Submitted Data
Magic Quotes
Hiding PHP
Keeping Current
Features
HTTP authentication with PHP
Cookies
Sessions
Dealing with XForms
Handling file uploads
Using remote files
Connection handling
https://www.php.net/manual/es/function.parse-str.php 1/22
24/9/2020 PHP: parse_str - Manual
Function Reference
Affecting PHP's Behaviour
Audio Formats Manipulation
Authentication Services
Command Line Specific Extensions
Compression and Archive Extensions
Credit Card Processing
Cryptography Extensions
Database Extensions
Date and Time Related Extensions
File System Related Extensions
Human Language and Character Encoding Support
Image Processing and Generation
Mail Related Extensions
Mathematical Extensions
Non-Text MIME Output
Process Control Extensions
Other Basic Extensions
Other Services
Search Engine Extensions
Server Specific Extensions
Session Extensions
Text Processing
Variable and Type Related Extensions
Web Services
Windows Only Extensions
XML Manipulation
GUI Extensions
Keyboard Shortcuts
?
This help
j
Next menu item
k
Previous menu item
gp
Previous man page
gn
Next man page
G
Scroll to bottom
gg
Scroll to top
gh
Goto homepage
gs
Goto search
(current page)
/
Focus search box
https://www.php.net/manual/es/function.parse-str.php 2/22
24/9/2020 PHP: parse_str - Manual
print »
« ord
Manual de PHP
Referencia de funciones
Procesamiento de texto
Strings
Funciones de strings
parse_str
(PHP 4, PHP 5, PHP 7)
Descripción ¶
Analiza str como si fuera un string de consulta pasado por medio de un URL y establece variables en el
ámbito actual.
Nota:
Nota:
Parámetros ¶
str
El string de entrada.
arr
Si el segundo parámetro arr está presente, es su lugar las variables serán almacenadas en esta variable
como elementos de array.
Valores devueltos ¶
Ejemplos ¶
https://www.php.net/manual/es/function.parse-str.php 3/22
24/9/2020 PHP: parse_str - Manual
<?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
?>
Ver también ¶
parse_url() - Analiza un URL y devuelve sus componentes
pathinfo() - Devuelve información acerca de la ruta de un fichero
http_build_query() - Generar una cadena de consulta codificada estilo URL
get_magic_quotes_gpc() - Obtiene el valor actual de configuración de magic_quotes_gpc
urldecode() - Decodifica una cadena cifrada como URL
add a note
up
down
78
Evan K ¶
13 years ago
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');
<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=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:
https://www.php.net/manual/es/function.parse-str.php 4/22
24/9/2020 PHP: parse_str - Manual
<?php
function proper_parse_str($str) {
# result array
$arr = array();
$query = proper_parse_str($_SERVER['QUERY_STRING']);
?>
up
down
13
alxcube at gmail dot com ¶
4 years ago
if you need custom arg separator, you can use this function. it returns parsed query as
associative array.
<?php
/**
* Parses http query string into an array
*
* @author Alxcube <alxcube@gmail.com>
*
* @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)
{
https://www.php.net/manual/es/function.parse-str.php 5/22
24/9/2020 PHP: parse_str - Manual
$result = array();
$parts = explode($argSeparator, $queryString);
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;
}
$target = &$target[$index];
}
if (is_array($target)) {
$target[] = $paramValue;
} else {
$target = $paramValue;
}
}
https://www.php.net/manual/es/function.parse-str.php 6/22
24/9/2020 PHP: parse_str - Manual
return $result;
}
?>
up
down
18
shagshag ¶
8 years ago
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.
up
down
9
zweibieren at yahoo dot com ¶
5 years ago
If the arr argument is provided, all its existing elements are removed.
up
down
12
Olivier Mengué ¶
13 years ago
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.
up
down
3
tobsn at php dot net ¶
12 years ago
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!
up
down
6
¶
15 years ago
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);
?>
Results in:
url1: action=search&interest[]=sports&interest[]=music&sort=id
url2: action=search&interest[0]=sports&interest[1]=music&sort=interest
<?php
// Note: "[" = %5B, "]" = %5D
/*
"v][=a" produces ("[" gets replaced by "_"):
Array
(
[v]_] => a
)
*/
parse_str("v%5D%5B=a", $r);
print_r($r);
/*
"v][[=a" produces (first "[" gets replaced by "_", but not all following):
Array
(
[v]_[] => a
)
*/
parse_str("v%5D%5B%5B=a", $r);
print_r($r);
?>
up
down
1
kent at nospam dot ioflux dot com ¶
15 years ago
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
*/
https://www.php.net/manual/es/function.parse-str.php 8/22
24/9/2020 PHP: parse_str - Manual
/**
* 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;
}
https://www.php.net/manual/es/function.parse-str.php 9/22
24/9/2020 PHP: parse_str - Manual
/**
* 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($a, 0, $n);
return $result;
}
?>
up
down
2
jrgns at jadeit dot co dot za ¶
8 years ago
The array to be populated does not need to be defined before calling the function:
<?php
error_reporting(E_ALL | E_STRICT);
parse_str('var=value', $array);
?>
13 years ago
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
$sessid = session_id();
if (!empty($parent) || empty($sessid))
return implode('&', $params);
?>
Note that the function will also append the session ID to the query string if it needs to
be.
up
down
1
helpmepro1 at gmail dot com ¶
12 years ago
<?
//by shimon doodkin
$url_form=url_to_form($url);
echo '<form action="'.$url_form['action'].'" method="get">';
https://www.php.net/manual/es/function.parse-str.php 11/22
24/9/2020 PHP: parse_str - Manual
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);
}
?>
up
down
1
chris at mcfadyen dot ca ¶
12 years ago
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('=', $pair, 2);
global $$name;
$$name = $value;
}
}
?>
up
down
1
PEPE_RIVAS at repixel dot net ¶
14 years ago
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:
https://www.php.net/manual/es/function.parse-str.php 12/22
24/9/2020 PHP: parse_str - Manual
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
?>
up
down
0
twiddly ¶
2 years ago
proper_parse_str works great and I like that it doesn't replace spaces with underbars, but
should urldecode $value
up
down
0
php at voodoolabs dot net ¶
13 years ago
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
<?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);
}
up
down
-1
chris at mcfadyen dot ca ¶
12 years ago
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('=', $pair, 2);
// 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($$name, addslashes(urldecode($value)));
}
// Variables
} else {
// Declare or overwrite the global variable defined by $name
global $$name;
$$name = addslashes(urldecode($value));
}
}
}
?>
up
down
-1
lenix.de ¶
https://www.php.net/manual/es/function.parse-str.php 15/22
24/9/2020 PHP: parse_str - Manual
13 years ago
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:
<?php
$virtual_path = substr(
$_SERVER['REQUEST_URI'],
strlen( dirname( $_SERVER['PHP_SELF'] ) ) + 1
);
if( ($pos = strpos( $virtual_path, '?' )) !== false ) {
parse_str( substr( $virtual_path, $pos + 1 ), $_GET );
$_REQUEST = array_merge( $_REQUEST, $_GET );
$virtual_path = substr( $virtual_path, 0, $pos );
}
echo $virtual_path."\n\n";
print_r( $_REQUEST );
?>
<?
parse_str ($_SERVER['argv'][1], $GLOBALS['_GET']);
parse_str ($_SERVER['argv'][2], $GLOBALS['_POST']);
?>
Cheers!
up
down
-2
Michal Zalewski ¶
13 years ago
Vladimir Kornea:
Try use html_entity_decode()
$str = 'first=value&arr[]=foo+bar&arr[]=baz';
https://www.php.net/manual/es/function.parse-str.php 16/22
24/9/2020 PHP: parse_str - Manual
parse_str(html_entity_decode($str), $output);
print_r($output);
Array
(
[first] => value
[arr] => Array
(
[0] => foo bar
[1] => baz
)
)
up
down
-3
Will Voelcker ¶
10 years ago
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;
}
?>
/**
* 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);
https://www.php.net/manual/es/function.parse-str.php 17/22
24/9/2020 PHP: parse_str - Manual
<?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;
}
}
<?php
class someclass
{
var $arr;
function someclass($a_query_string)
{
https://www.php.net/manual/es/function.parse-str.php 18/22
24/9/2020 PHP: parse_str - Manual
parse_str($a_query_string, $this->arr);
}
function output()
{
echo $this->arr['action'];
}
}
(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.)
up
down
-8
Vladimir Kornea ¶
14 years ago
This function is confused by ampersands (&) being encoded as HTML entities (&).
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
print_r($output);
Array
(
[first] => value
[amp;arr] => Array
(
[0] => foo bar
[1] => baz
)
)
up
down
-2
jgbreezer at gmail dot com ¶
13 years ago
Vladimir Kornea wrote on 8 Sep 2006:
"This function is confused by ampersands (&) being encoded as HTML entities (&)"
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).
up
down
https://www.php.net/manual/es/function.parse-str.php 19/22
24/9/2020 PHP: parse_str - Manual
-3
markc ¶
7 years ago
Beware using parse_str in a function that has vars passed by reference. It seems that
parse_str actually creates new vars even if vars of the same name exist. If you pass by
ref vars of the same name as those in a query string being parsed new LOCAL vers will be
created and you won't get any values passed back to the caller (relates to what Maikel
mentioned below)
An unrealistic example (vaguely related to what I was doing when I found this out)...
function get_title($query,&$title)
{
parse_str($query);
$title=str_replace("_"," ",$title);
}
$title="foo";
$query = "context=something&title=Title_of_Something";
get_title($query,$title);
Funciones de strings
addcslashes
addslashes
bin2hex
chop
chr
chunk_split
convert_cyr_string
convert_uudecode
convert_uuencode
count_chars
crc32
crypt
echo
explode
fprintf
get_html_translation_table
hebrev
hebrevc
hex2bin
html_entity_decode
htmlentities
htmlspecialchars_decode
htmlspecialchars
implode
join
lcfirst
levenshtein
localeconv
ltrim
md5_file
md5
metaphone
money_format
https://www.php.net/manual/es/function.parse-str.php 20/22
24/9/2020 PHP: parse_str - Manual
nl_langinfo
nl2br
number_format
ord
parse_str
print
printf
quoted_printable_decode
quoted_printable_encode
quotemeta
rtrim
setlocale
sha1_file
sha1
similar_text
soundex
sprintf
sscanf
str_getcsv
str_ireplace
str_pad
str_repeat
str_replace
str_rot13
str_shuffle
str_split
str_word_count
strcasecmp
strchr
strcmp
strcoll
strcspn
strip_tags
stripcslashes
stripos
stripslashes
stristr
strlen
strnatcasecmp
strnatcmp
strncasecmp
strncmp
strpbrk
strpos
strrchr
strrev
strripos
strrpos
strspn
strstr
strtok
strtolower
strtoupper
strtr
substr_compare
substr_count
substr_replace
substr
https://www.php.net/manual/es/function.parse-str.php 21/22
24/9/2020 PHP: parse_str - Manual
trim
ucfirst
ucwords
vfprintf
vprintf
vsprintf
wordwrap
https://www.php.net/manual/es/function.parse-str.php 22/22