You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用array_shift从路径拆分数组提取ContactController文件名?

解决路径提取文件名的问题

嘿,我懂你碰到的小麻烦啦!你现在的问题出在用错了数组函数——array_shift()是用来移除并返回数组的第一个元素,但你要的文件名ContactController是数组的最后一个元素,所以肯定拿不到正确结果呀!

问题分析

你拆分路径后得到的数组是:

array(2) { 
  [0]=> string(4) "Info" 
  [1]=> string(17) "ContactController" 
}

用array_shift($path_explode)会把第一个元素"Info"赋值给$file,这显然不是你想要的控制器文件名。

正确的解决方法

你需要用array_pop()函数,它会移除并返回数组的最后一个元素,正好对应路径里的文件名:

<?php
$path_to_controller = 'Info/ContactController';
$path_explode = explode('/', str_replace('./', '', (string)$path_to_controller));
// 替换array_shift为array_pop
$file = array_pop($path_explode);
var_dump($file); // 输出:string(17) "ContactController"
?>

额外小技巧

如果不需要修改原数组(也就是不想把文件名从$path_explode里移除),可以用end()函数直接获取最后一个元素:

$file = end($path_explode);
var_dump($file); // 同样得到"ContactController"

这个方法更适合只需要读取文件名、保留原数组的场景。

内容的提问来源于stack exchange,提问作者Mecom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:47:55