How to separate filename from path? basename() ver

2019-07-12 21:00发布

问题:

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?