Home > Backend Development > PHP Tutorial > Detailed explanation of how to obtain url instance in php

Detailed explanation of how to obtain url instance in php

伊谢尔伦
Release: 2023-03-11 14:24:01
Original
2705 people have browsed it

When the URL parameters are known, we can use $_GET to obtain the corresponding parameter information ($_GET['name']) according to our own situation; then, how to obtain the parameter information on the URL under unknown circumstances Woolen cloth?

The first method is to use the $_SERVER built-in array Variables

The relatively primitive $_SERVER['QUERY_STRING'] is used to obtain URL parameters. This variable is usually used The data returned will be similar to this: name=tank&sex=1
If you need to include the file name, you can use $_SERVER["REQUEST_URI"](return similar to:/index.php?name=tank&sex =1)

Second, use pathinfobuilt-in function

<?php
$test = pathinfo("http://localhost/index.php");
print_r($test);
/*
结果如下
Array
(
     [dirname] => http://localhost //url的路径
     [basename] => index.php  //完整文件名
     [extension] => php  //文件名后缀
     [filename] => index //文件名
)
*/
?>
Copy after login

Third, use parse_url built-in function

<?php
$test = parse_url("http://localhost/index.php?name=tank&sex=1#top");
print_r($test);
/*
结果如下
Array
(
     [scheme] => http //使用什么协议
     [host] => localhost //主机名
     [path] => /index.php //路径
     [query] => name=tank&sex=1 // 所传的参数
     [fragment] => top //后面根的锚点
)
*/
?>
Copy after login

Fourth, use basename built-in function

<?php
$test = basename("http://localhost/index.php?name=tank&sex=1#top");
echo $test;
/*
结果如下
index.php?name=tank&sex=1#top
*/
?>
Copy after login

In addition, you can also obtain the required value through regular matching processing. This method is more accurate and efficiency is not considered for the time being. . .
The following expands the regular processing method in practice:

<?php
preg_match_all("/(\w+=\w+)(#\w+)?/i","http://localhost/index.php?name=tank&sex=1#top",$match);
print_r($match);
/*
结果如下
Array
(
    [0] => Array
        (
            [0] => name=tank
            [1] => sex=1#top
        )
    [1] => Array
         (
            [0] => name=tank
             [1] => sex=1
         )
     [2] => Array
        (
             [0] =>
            [1] => #top
        )
)
*/
?>
Copy after login

The above is the detailed content of Detailed explanation of how to obtain url instance in php. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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