wp_parse_str()
云策文档标注
概述
wp_parse_str() 函数用于将字符串解析为变量并存储到数组中,常用于处理查询字符串。它基于 PHP 的 parse_str() 函数,并添加了 WordPress 过滤器钩子。
关键要点
- 函数接受两个参数:$input_string(必需,要解析的字符串)和 $result(必需,存储解析后变量的数组引用)。
- 内部调用 parse_str() 函数进行解析,并通过 apply_filters('wp_parse_str', $result) 应用过滤器,允许开发者修改结果数组。
- 常用于从 URL 查询字符串中提取参数,例如与 wp_parse_url() 结合使用。
- 自 WordPress 2.2.1 版本引入,是核心函数之一。
代码示例
$url = 'https://xyz.com/?a=10&b=20';
$parse_url = wp_parse_url( $url );
$args = [];
wp_parse_str( $parse_url[ 'query' ], $args );
// $args 结果为 Array( [a] => 10, [b] => 20 )
原文内容
Parses a string into variables to be stored in an array.
Parameters
$input_stringstringrequired-
The string to be parsed.
$resultarrayrequired-
Variables will be stored in this array.
Source
function wp_parse_str( $input_string, &$result ) {
parse_str( (string) $input_string, $result );
/**
* Filters the array of variables derived from a parsed string.
*
* @since 2.2.1
*
* @param array $result The array populated with variables.
*/
$result = apply_filters( 'wp_parse_str', $result );
}
Hooks
- apply_filters( ‘wp_parse_str’, array $result )
-
Filters the array of variables derived from a parsed string.
Changelog
| Version | Description |
|---|---|
| 2.2.1 | Introduced. |
Skip to note 2 content
Krupal Panchal
Let’s say, you have an URL with query parameters. And you need query parameter values in an Array.
$url = 'https://xyz.com/?a=10&b;=20'; $parse_url = wp_parse_url( $url ); // Value of $parse_url // Array // ( // [scheme] => https // [host] => xyz.com // [path] => / // [query] => a=10&b;=20 // ) $args = []; wp_parse_str( $parse_url[ 'query' ], $args ); // Value of $args // Array // ( // [a] => 10 // [b] => 20 // )