How to separate filename from path? basename() ver

2019-07-12 20:23发布

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条回答
太酷不给撩
2楼-- · 2019-07-12 21:10

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?

查看更多
登录 后发表回答