如何从路径中分离文件名? basename()与带有array_pop()的preg_split() [英] How to separate filename from path? basename() versus preg_split() with array_pop()

查看:61
本文介绍了如何从路径中分离文件名? basename()与带有array_pop()的preg_split()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果此函数的实际作用可能写在两行中,为什么要在PHP脚本中使用basename():

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)

我想念什么吗?

但是我猜上面的代码可能无法正确运行,如果文件名中包含一些\/.但这不可能,对吧?

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

推荐答案

PHP可以在具有许多不同文件系统和命名约定的许多不同系统上运行.无论平台如何,使用basename()之类的功能都可以保证(或至少应该保证)正确的结果.这样可以提高代码的可移植性.

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.

还要将一个简单的basename()调用与您的代码进行比较-可读性更高,并且对于其他程序员而言,代码应该做什么?

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?

这篇关于如何从路径中分离文件名? basename()与带有array_pop()的preg_split()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆