How does PHP parse a url and get its parameters? (code example)

青灯夜游
Release: 2023-04-04 13:12:02
forward
2756 people have browsed it

The content of this article is to introduce how PHP parses the URL and obtains its parameters? (Code example), let everyone know how to parse url and get url parameters in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Here are two ways to operate the URL:

1. After getting a complete URL, how to parse the URL to get the parameters inside.

/**
 * 解析url中参数信息,返回参数数组
 */
function convertUrlQuery($query)
{
   $queryParts = explode('&', $query);

   $params = array();
   foreach ($queryParts as $param) {
      $item = explode('=', $param);
      $params[$item[0]] = $item[1];
   }

   return $params;
}
Copy after login

2. How to splice an array into a url and pass it.

/**
 * 把数组拼接成url参数形式
 */
function getUrlQuery($array_query)
{
   $tmp = array();
   foreach ($array_query as $k => $param) {
      $tmp[] = $k . '=' . $param;
   }
   $params = implode('&', $tmp);
   return $params;
}
Copy after login

Test call:

$url = 'http://www.test.com/link?param1=1&param2=2&param3=3';
// 解析url,得到参数字符串
$url = parse_url($url);
// 字符串->数组
$param_arr = $this->convertUrlQuery($url['query']);
// 数组->字符串
$param_str = $this->getUrlQuery($param_arr);
Copy after login

Summary: The above is the entire content of this article, I hope it can be helpful to everyone’s learning helped. Recommended more related video tutorials: PHP tutorial!

The above is the detailed content of How does PHP parse a url and get its parameters? (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!