【php

您所在的位置:网站首页 玄幻无敌大反派TXT下载 【php

【php

2024-02-07 10:15| 来源: 网络整理| 查看: 265

使用三种以上方式获取一个文件的扩展名

$file = 'siyuantlw/程序设计.php';

1.使用strrchr函数

strrchr() 函数查找字符串在另一个字符串中最后一次出现的位置,并返回从该位置到字符串结尾的所有字符。

function getExt1($file){ return substr(strrchr($file,'.'),1); } echo getExt1($file);

2.strripos函数

strripos() 函数查找字符串在另一字符串中最后一次出现的位置。

注释:strripos() 函数对大小写不敏感。还有另外一个版本,strrpos() - 查找字符串在另一字符串中最后一次出现的位置(区分大小写)

function getExt2($file){ return substr($file,strripos($file,'.')+1); } echo getExt2($file);

3.strrev函数

strrev() 函数反转字符串。

配合strpos函数,stripos() - 查找字符串在另一字符串中第一次出现的位置(不区分大小写)

function getExt3($file){ return strrev(substr(strrev($file),0,stripos(strrev($file),'.'))); } echo getExt3($file);

另外还可以通过数组函数来实现

4.array_pop函数

array_pop() 函数删除数组中的最后一个元素。

配合explode

explode(separator,string,limit)

explode() 函数把字符串打散为数组。 注释:"separator" 参数不能是空字符串。

注:下面的写法是不行的

function getExt4($file){ return array_pop(explode('.',$file)); } #这样写,会有警告,Notice: Only variables should be passed by reference in /home/wwwroot/remote_test/index.php on line 146

最好写下下面的形式:

function getExt4($file){ $arr = explode('.',$file); return array_pop($arr); } echo(getExt4($file)); /* 这样写不会再提示警告,因为array_pop的参数是按址传递的,所以需要一个变量才行。 function array_pop (array &$array) {} */

5.使用pathinfo函数

function getExt5($file){ // $arr = pathinfo($file); // return $arr['extension']; // 或者写成下面这种 return pathinfo($file,PATHINFO_EXTENSION); } echo getExt5($file);

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3