parse_str() - 将字符串解析成多个变量 - php 字符串函数
parse_str()
(PHP 4, PHP 5, PHP 7)
将字符串解析成多个变量
说明
parse_str (string $encoded_string [, array &$result ] ) : void如果 $encoded_string 是 URL 传递入的查询字符串(query string),则将它解析为变量并设置到当前作用域(如果提供了 $result 则会设置到该数组里 )。
参数
$encoded_string
输入的字符串。
$result如果设置了第二个变量 $result, 变量将会以数组元素的形式存入到这个数组,作为替代。
Warning极度不建议 在没有 $result 参数的情况下使用此函数,并且在 PHP 7.2 中将废弃不设置参数的行为。
在函数中动态设置变量会和 register_globals 有同样的问题。
阅读「安全」中 使用 Register Globals 的章节,解释了它为什么是危险的。
返回值
没有返回值。
更新日志
版本 | 说明 |
---|---|
7.2.0 | 不带第二个参数的情况下使用 parse_str() 会产生 E_DEPRECATED 警告。 |
范例
parse_str() 的使用
由于 PHP 的变量名不能带「点」和「空格」,所以它们会被转化成下划线。 用本函数带 $result 参数,也会应用同样规则到数组的键名。
parse_str() 名称改写
注释
Note:
所有创建的变量(或者在设置第二个参数的情况下,返回数组里的值), 都已经 urldecode() 了。
Note:
要获取当前的 QUERY_STRING,可以使用 $_SERVER['QUERY_STRING'] 变量。 所以你可能想要阅读 来自 PHP 之外的变量这个章节。
Note:
本函数受 magic_quotes_gpc 设置的影响, 和 $_GET、 $_POST 在 PHP 中填充变量相似, parse_str() 也使用了同样的机制。
参见
parse_url()
解析 URL,返回其组成部分pathinfo()
返回文件路径的信息http_build_query()
生成 URL-encode 之后的请求字符串urldecode()
解码已编码的 URL 字符串
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: Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect. 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:
if you need custom arg separator, you can use this function. it returns parsed query as associative array.
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!
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 the arr argument is provided, all its existing elements are removed.
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.
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: 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.)
Note that the characters "." and " " (empty space) will be converted to "_". The characters "[" and "]" have special meaning: They represent arrays but there seems to be some weird behaviour, which I don't really understand:
The array to be populated does not need to be defined before calling the function: This will not produce a notice.
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. Note that the function will also append the session ID to the query string if it needs to be.
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 &
proper_parse_str works great and I like that it doesn't replace spaces with underbars, but should urldecode $value
If you wish a version of parse_str sans magic quotes, the following will do the trick:
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]
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).
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.
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.
You may want to parse the query string into an array. Note that these functions support nested arrays of unlimited levels ;)
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: And call your script by: /usr/local/bin/php /path/to/script.php "id=45&action=delete" "formsubmitted=true" Cheers!
Vladimir Kornea: Try use html_entity_decode() $str = 'first=value&arr[]=foo+bar&arr[]=baz'; parse_str(html_entity_decode($str), $output); print_r($output); Array ( [first] => value [arr] => Array ( [0] => foo bar [1] => baz ) )
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.
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 // guido 'lenix' boehm
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: It may need adapting to handle various edge cases.
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; }
This does not work as expected. Use this instead.
parse_str() is confused by ampersands (&) being encoded as HTML entities (&). 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.)
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 ) )
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); echo $title .... "foo"
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!