這篇文章主要介紹了PHP解析URL函數parse_url和parse_str,并給出了相應的示例,非常的實用,有需要的朋友們可以參考下
PHP中有兩個方法可以用來解析URL,分別是parse_url和parse_str。
parse_url
解析 URL,返回其組成部分
mixed parse_url ( string $url [, int $component = -1 ] )
本函數解析一個 URL 并返回一個關聯數組,包含在 URL 中出現的各種組成部分。
本函數不是用來驗證給定 URL 的合法性的,只是將其分解為下面列出的部分。不完整的 URL 也被接受,parse_url() 會嘗試盡量正確地將其解析。
參數
url 要解析的 URL。無效字符將使用 _ 來替換。
component 指定 PHP_URL_SCHEME、 PHP_URL_HOST、 PHP_URL_PORT、 PHP_URL_USER、 PHP_URL_PASS、 PHP_URL_PATH、 PHP_URL_QUERY 或 PHP_URL_FRAGMENT 的其中一個來獲取 URL 中指定的部分的 string。 (除了指定為 PHP_URL_PORT 后,將返回一個 integer 的值)。
返回值
對嚴重不合格的 URL,parse_url() 可能會返回 FALSE。
如果省略了 component 參數,將返回一個關聯數組 array,在目前至少會有一個元素在該數組中。數組中可能的鍵有以下幾種:
scheme - 如 http
host
port
user
pass
path
query - 在問號 ? 之后
fragment - 在散列符號 # 之后
如果指定了 component 參數, parse_url() 返回一個 string (或在指定為 PHP_URL_PORT 時返回一個 integer)而不是 array。如果 URL 中指定的組成部分不存在,將會返回 NULL。
實例代碼如下:
- <?php
- $url = 'http://username:password@hostname/path?arg=value#anchor';
- print_r(parse_url($url));
- echo parse_url($url, PHP_URL_PATH);
- ?>
以上例程會輸出:
- Array
- (
- [scheme] => http
- [host] => hostname
- [user] => username
- [pass] => password
- [path] => /path
- [query] => arg=value
- [fragment] => anchor
- )
- /path
parse_str
將字符串解析成多個變量
void parse_str ( string $str [, array &$arr ] )
如果 str 是 URL 傳遞入的查詢字符串(query string),則將它解析為變量并設置到當前作用域。
獲取當前的 QUERY_STRING,你可以使用 $_SERVER['QUERY_STRING'] 變量。
參數
str 輸入的字符串。
arr 如果設置了第二個變量 arr,變量將會以數組元素的形式存入到這個數組,作為替代。
實例代碼如下:
- <?php
- $str = "first=value&arr[]=foo+bar&arr[]=baz";
- parse_str($str);
- echo $first; // value
- echo $arr[0]; // foo bar
- echo $arr[1]; // baz
- parse_str($str, $output);
- echo $output['first']; // value
- echo $output['arr'][0]; // foo bar
- echo $output['arr'][1]; // baz
- ?>
前一段時間在讀php-resque的源碼,看到了在其中對這兩個的方法的應用,感覺用的很好,用來解析redis鏈接的設置。
redis鏈接的格式是:redis://user:pass@host:port/db?option1=val1&option2=val2,是不是和URL一樣,所以用以上兩個方法很容易解析。
地址: https://github.com/chrisboulton/php-resque/blob/master/lib/Resque/Redis.php
代碼如下:
- /**
- * Parse a DSN string, which can have one of the following formats:
- *
- * - host:port
- * - redis://user:pass@host:port/db?option1=val1&option2=val2
- * - tcp://user:pass@host:port/db?option1=val1&option2=val2
- *
- * Note: the 'user' part of the DSN is not used.
- *
- * @param string $dsn A DSN string
- * @return array An array of DSN compotnents, with 'false' values for any unknown components. e.g.
- * [host, port, db, user, pass, options]
- */
- public static function parseDsn($dsn)
- {
- if ($dsn == '') {
- // Use a sensible default for an empty DNS string
- $dsn = 'redis://' . self::DEFAULT_HOST;
- }
- $parts = parse_url($dsn);
- // Check the URI scheme
- $validSchemes = array('redis', 'tcp');
- if (isset($parts['scheme']) && ! in_array($parts['scheme'], $validSchemes)) {
- throw new /InvalidArgumentException("Invalid DSN. Supported schemes are " . implode(', ', $validSchemes));
- }
- // Allow simple 'hostname' format, which `parse_url` treats as a path, not host.
- if ( ! isset($parts['host']) && isset($parts['path'])) {
- $parts['host'] = $parts['path'];
- unset($parts['path']);
- }
- // Extract the port number as an integer
- $port = isset($parts['port']) ? intval($parts['port']) : self::DEFAULT_PORT;
- // Get the database from the 'path' part of the URI
- $database = false;
- if (isset($parts['path'])) {
- // Strip non-digit chars from path
- $database = intval(preg_replace('/[^0-9]/', '', $parts['path']));
- }
- // Extract any 'user' and 'pass' values
- $user = isset($parts['user']) ? $parts['user'] : false;
- $pass = isset($parts['pass']) ? $parts['pass'] : false;
- // Convert the query string into an associative array
- $options = array();
- if (isset($parts['query'])) {
- // Parse the query string into an array
- parse_str($parts['query'], $options);
- }
- return array(
- $parts['host'],
- $port,
- $database,
- $user,
- $pass,
- $options,
- );
- }
以上就是個人關于php解析URL函數parse_url和parse_str的理解,這里記錄下來,分享給大家,希望對小伙伴有所幫助。
新聞熱點
疑難解答