>  기사  >  백엔드 개발  >  PHP는 URL을 어떻게 구문 분석합니까? URL을 구문 분석하는 5가지 방법 소개

PHP는 URL을 어떻게 구문 분석합니까? URL을 구문 분석하는 5가지 방법 소개

青灯夜游
青灯夜游앞으로
2020-07-18 15:55:098525검색

PHP는 URL을 어떻게 구문 분석합니까? URL을 구문 분석하는 5가지 방법 소개

PHP가 URL을 구문 분석하는 여러 가지 방법

1. $_SERVER 내장 배열 변수를 사용하세요

방문:
http://localhost/test.php?m=admin&c=index&a = lists & catid = 1 & page = 1

//URL的参数
echo $_SERVER['QUERY_STRING'];
返回:
m=admin&c=index&a=lists&catid=1&page=1
//包含文件名
echo $_SERVER["REQUEST_URI"];

return :

/test.php?m=admin&c=index&a=lists&catid=1&page=1


2

반환:

echo "
";
$url = 'http://localhost/test.php?m=admin&c=index&a=lists&catid=1&page=1#top';
var_export(pathinfo($url));
4. 기본 제공 함수

array (
  'dirname' => 'http://localhost',
  'basename' => 'test.php?m=admin&c=index&a=lists&catid=1&page=1#top',
  'extension' => 'php?m=admin&c=index&a=lists&catid=1&page=1#top',
  'filename' => 'test',
)

사용:

echo "
";
$url = 'http://localhost/test.php?m=admin&c=index&a=lists&catid=1&page=1#top';
var_export(parse_url($url));
5. 정규 일치

array (
  'scheme' => 'http',
  'host' => 'localhost',
  'path' => '/test.php',
  'query' => 'm=admin&c=index&a=lists&catid=1&page=1',
  'fragment' => 'top',
)

반환:

echo "
";
$url = 'http://localhost/test.php?m=admin&c=index&a=lists&catid=1&page=1#top';
var_export(basename($url));

일반적인 URL 처리 방법

test.php?m=admin&c=index&a=lists&catid=1&page=1#top
예:

echo "
";
$url = 'http://localhost/test.php?m=admin&c=index&a=lists&catid=1&page=1#top';
preg_match_all("/(\w+=\w+)(#\w+)?/i",$url,$match);
var_export($match);

반환:

array (
  0 => 
  array (
    0 => 'm=admin',
    1 => 'c=index',
    2 => 'a=lists',
    3 => 'catid=1',
    4 => 'page=1#top',
  ),
  1 => 
  array (
    0 => 'm=admin',
    1 => 'c=index',
    2 => 'a=lists',
    3 => 'catid=1',
    4 => 'page=1',
  ),
  2 => 
  array (
    0 => '',
    1 => '',
    2 => '',
    3 => '',
    4 => '#top',
  ),
)
rrree 반환:
/**
 * 将字符串参数变为数组
 * @param $query
 * @return array
 */
function convertUrlQuery($query)
{
    $queryParts = explode('&', $query);
    $params = array();
    foreach ($queryParts as $param) {
        $item = explode('=', $param);
        $params[$item[0]] = $item[1];
    }
    return $params;
}

/**
 * 将参数变为字符串
 * @param $array_query
 * @return string
 */
function getUrlQuery($array_query)
{
    $tmp = array();
    foreach ($array_query as $k => $param) {
        $tmp[] = $k . '=' . $param;
    }
    $params = implode('&', $tmp);
    return $params;
}
추천 관련 튜토리얼: "

PHP Tutorial

"

위 내용은 PHP는 URL을 어떻게 구문 분석합니까? URL을 구문 분석하는 5가지 방법 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 cnblogs.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제