How to separate filename from path? basename() versus preg_split() with array_pop()

℡╲_俬逩灬. 提交于 2019-12-11 03:45:36

问题


Why use basename() in PHP scripts if what this function is actually doing may be written in 2 lines:

$subFolders = preg_split("!\\\|\\/!ui", $path);  // explode on `\` or `/`
$name = array_pop($subFolder);  // extract last element's value (filename)

Am I missing something?

However I guess this code above may not work correctly if file name has some \ or / in it. But that's not possible, right?


回答1:


PHP may run on many different systems with many different filesystems and naming conventions. Using a function like basename() guarantees (or at least, is supposed to guarantee) a correct result regardless of the platform. This increases the code's portability.

Also, compare a simple basename() call to your code - which is more readable, and more obvious to other programmers in regards to what it is supposed to do?



来源:https://stackoverflow.com/questions/20859628/how-to-separate-filename-from-path-basename-versus-preg-split-with-array-po

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!