1. 写一个函数,尽可能高效的,从一个标准 url 里取出文件的扩展名
  例如: http://www.phpddt.com/abc/de/fg.php?id=1 需要取出 php 或 .php

$url = 'http://www.baidu.com/wang/liu/4.php?i=90';
$urlArr = parse_url($url);
$ext = pathinfo($urlArr['path'],PATHINFO_EXTENSION);
echo $ext;
(1)函数:mixed parse_url ( string $url [, int $component = -1 ] )

 参数:

​  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​​ 的值)。     ps:

  • 只有$url 参数时,返回一个关联数组
  • $url,$component两个参数都有时,返回一个string或者integer 类型
<?php
$url = '//www.example.com/dir/path.php?googleguy=googley';

// 在 5.4.7 之前这会输出路径 "//www.example.com/path"
var_dump(parse_url($url));
?>

 

输出

 

 

array(3) {
["host"]=>
string(15) "www.example.com"
["path"]=>
string(5) "/dir/path.php"
["query"]=> string(17)
"googleguy=googley"
}

(2)pathinfo() 函数以数组的形式返回文件路径的信息。

pathinfo(path,options)
path   可选。规定要返回的数组元素。默认是 all。
options  可能的值:
  • PATHINFO_DIRNAME - 只返回 dirname
  • PATHINFO_BASENAME - 只返回 basename
  • PATHINFO_EXTENSION - 只返回 extensio
例子 1
<?php
print_r(pathinfo("/testweb/test.txt"));
?>
输出:

Array
(
[dirname] => /testweb
[basename] => test.txt
[extension] => txt
)
例子 2
<?php
print_r(pathinfo("/testweb/test.txt",PATHINFO_BASENAME));
?>
输出:

test.txt