In this article, we will explore the parse_str
function in PHP. It is used to convert the GET request query string into usable variables.
In day-to-day PHP development, you often need to deal with query strings, which is how data is passed to a script in a URL via a GET request. When passing query string in URL, PHP provides super global $_GET
variable which contains all query parameters as PHP variables, so you can easily read the parameters available in query string. However, sometimes you need to process the raw query string and convert it into a variable.
In PHP, there are a few different ways to accomplish this. You can use the explode
function to split the query string by &
characters and then by =
characters. But there's an easier way: PHP provides the parse_str
function, which allows you to parse the query string in a single call.
Today, we will discuss the parse_str
function in detail, as well as a few practical examples.
Syntax: parse_str
Function
Let’s take a look at the syntax of the parse_str
function:
parse_str(string $string, array &$result): void
As you can see, parse_str
has two parameters. The first parameter is the input string, which should be in query string format, e.g. name=Wilson&color=blue
.
The second parameter is an array that will be populated by the variables parsed in the query string.
It is important to note that the parse_str
function does not return anything, so you must use the second parameter to initialize the result of the function. Prior to PHP 7.2, the second argument was optional, omitting it told parse_str
to return the resulting value as a variable in local scope, but starting with PHP 7.2, this is a mandatory argument.
Additionally, the parse_str
function always decodes URL-encoded variables, so you do not need to use the urldecode
function. In addition to this, if you have a long input query string, it may throw input variables exceeds X
error. In this case, check the max_input_vars configuration value in the php.ini
configuration file and adjust it according to your requirements.
让我们在下一节中看几个现实世界的示例。
parse_str
在本节中,我们将通过几个实际示例来演示如何使用 parse_str
函数。
一个简单的例子
让我们从一个简单的示例开始,如以下代码片段所示。
<?php $string = 'first_name=John&last_name=Richards&age=30'; parse_str($string, $result); print_r($result); /** Output: Array ( [first_name] => John [last_name] => Richards [age] => 30 ) **/
如您所见, parse_str
函数解析 $string
查询字符串,并且 $result
填充有一个数组。变量名称被转换为数组键,变量值被分配给相应的数组键。
数组示例
很多时候,输入的查询字符串可能包含数组变量,parse_str
函数可以检测到它并将其转换为相应的数组变量。
<?php $string = 'foo=1&bar[]=1&bar[]=2'; parse_str($string, $result); print_r($result); /** $result Output: Array ( [foo] => 1 [bar] => Array ( [0] => 1 [1] => 2 ) ) **/
正如您在上面的示例中看到的,bar
变量在输入查询字符串中包含多个值,并且它被转换为相应的 $result['bar']
数组,如输出所示。
请注意,如果您在数组变量后不使用特殊的 []
语法,则 parse_str
会将其视为常规变量,并且仅保留字符串中的最后一个值。这与大多数查询字符串解析器的工作方式略有不同。
特殊字符示例
有时,输入查询字符串包含空格和点作为变量名称的一部分。但是,PHP 不允许变量名中包含空格和点,因此它们会被 parse_str
函数自动转换为下划线。
让我们看一下下面的示例来了解它是如何工作的。
<?php $string = 'my name=John&my.email=john@example.com'; parse_str($string, $result); print_r($result); /** $result Output: Array ( [my_name] => John [my_email] => john@example.com ) **/
如果您注意到,输入查询字符串变量中的空格和点字符将替换为数组键中的下划线 (_
) 字符。
URL 编码值示例
正如我们之前讨论的,parse_str
函数在解析期间始终对 URL 编码值进行解码。这意味着您不需要单独应用 urldecode
函数。
这是一个包含一些 URL 编码值的示例。
<?php $string = 'name=John%20Richards&profile_url=http%3A%2F%2Fexample.com%2Fmyprofile'; parse_str($string, $result); print_r($result); /** $result Output: Array ( [name] => John Richards [profile_url] => https://example.com/myprofile ) **/
如您所见,URL 编码的字符会自动转换为相应的字符。
结论
今天,我们讨论了 PHP 中的 parse_str
函数,该函数对于将查询字符串转换为变量非常有用。我希望您发现它对您自己的 PHP 编码很有用!
The above is the detailed content of How to use parse_str in PHP. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools