3 ways to parse URLs in PHP

【Foreword】

      This article summarizes three methods for parsing URLs, namely the pathinfo() method, the parse_url() method and the basename() method. Each method enumerates an example, and it is easier to understand the usage and techniques of these three functions through the example.

 

【main body】

1. Use pathinfo to parse the URL and return the various components of the file

<?  
    /* by www.manongjc.com/article/1119.html */  
    $test = pathinfo("http://localhost/index.php");  
    print_r($test);  
?>  

 The result is as follows:

Array  (  
 [dirname] => http://localhost //url path  
 [basename] => index.php //full file name  
 [extension] => php //File name suffix  
 [filename] => index //filename  
)

 Case 2:

<?php
    $path_part = pathinfo('c:/PHPTutorial/WWW/index.php');
    echo "File directory name: ".$path_part['dirname']."<br>";
    echo "Comprehensive file: ".$path_part['basename']."<br>";
    echo "File extension: ".$path_part['extension']."<br>";
    echo "Filename without extension: ".$path_part['filename']."<br>";
?>

 result:

File directory name: c:/PHPTutorial/WWW
File comprehensive: index.php
File extension: php
File name without extension: index

 

2. Use the parse_url() function to parse and parse the URL

<?php
    /* by http://www.manongjc.com*/  
    $test = parse_url("http://localhost/index.php?name=tank&sex=1#top");  
    print_r($test);  
?>  

 The result is as follows:

Array  (  
 [scheme] => http //what protocol to use  
 [host] => localhost //hostname  
 [path] => /index.php //path  
 [query] => name=tank&sex=1 // Parameters passed  
 [fragment] => top //The anchor point of the root behind  
)  

 

3. Use basename() to parse and return the file name

<?php
    $test = basename("http://localhost/index.php?name=tank&sex=1#top");  
    echo $test;  
?>  

 The result is as follows:

index.php?name=tank&sex=1#top

 

 

 

 

 

 

 

 

.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326130098&siteId=291194637