PHP提取文件名的基础方法
方案一:
若要获取不包含后缀的文件名,可直接参考以下代码实现:
核心在于调用basename()函数,该函数能直接从路径中分离出文件名。其标准语法为“basename(path,suffix)”,其中suffix参数用于指定需要移除的扩展名后缀。当传入如“.php”这样的参数时,函数会自动过滤掉对应的扩展名,从而只返回纯文件名。
<?php
$path = 'www.example.com/public_html/index.php';
$file = basename($path, ".php");
echo $file."\n";</code></pre>
方案二:
如果需要保留文件后缀名进行提取,可参考如下代码逻辑:
此方法主要依赖于strrchr和substr这两个函数的配合使用。
首先,strrchr函数负责定位目标字符在字符串中最后一次出现的位置,并返回从该位置开始直至字符串末尾的所有内容。
其次,substr函数用于截取字符串的子集,其基本语法格式为“substr(string,start,length)”,可根据起始位置和长度精确提取所需片段。
<pre class="brush:php;"><code class="language-php">
<?php
$path = 'www.example.com/public_html/index.php';
$file_name = substr(strrchr($path, "/"), 1);
echo $file_name."\n"; // "index.php"</code></pre>
关联知识拓展:
探讨如何利用PHP从URL字符串中精准截取路径及文件名和扩展名。
<pre class="brush:php;"><code class="language-php">
<?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");
?>
至此,关于PHP字符串中提取文件名的实例教程已分享完毕。如需了解更多PHP字符串处理相关内容,欢迎查阅本站历史文章或继续阅读后续推荐内容,感谢您的支持与关注!