PHP字符串中提取文件名的实例方法

第一种:

获取不带后缀的文件名,直接上代码:

就是直接用basename()函数就可以返回路径中的文件名部分,其语法是“basename(path,suffix)”,其中参数suffix就表示文件扩展名,如果文件有这个参数,则不会输出这个扩展名,显然这个参数我们设置是是“.php”。

<?php
$path = \'www.example.com/public_html/index.php\';
$file = basename($path, \".php\");
echo $file.\"\\n\";

第二种:

提取带有后缀名的文件名,代码如下:

该方法我们主要用到两个函数strrchr、substr。

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

substr函数用于返回字符串的一部分,语法“substr(string,start,length)”。

<?php
$path = \'www.example.com/public_html/index.php\';
$file_name = substr(strrchr($path, \"/\"), 1);
echo $file_name.\"\\n\"; // \"index.php\"

相关实例扩展:

php获取url字符串截取路径的文件名和扩展名

<?php
//获取连接里边的id
$url =\'http://www.rong123.com/cjbkscbsd/x_dfsdfs/24454_1_1.html\';
function getIdByUrl($url) {
    $id =\'\';
    $filename =basename($url,\".html\");
    $id =str_replace(\'-\',\'_\',$filename);
    if(strstr($id,\'_\')) {
        $conids =explode(\'_\',$id);
        $id =$conids[0];
    }
    return $id;
}
echo getIdByUrl($url).\'<hr/>\';
 
//获取完整文件名
echo basename($url).\'<hr/>\';
 
//获取没有后缀的文件名
echo basename($url,\".html\");
 
?>

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容