PHP:不带文件扩展名的文件名-最佳方法?
问题描述:
我正在尝试将文件名从不带扩展名的目录中拉出.
I am trying to pull the filename out of a directory without the extension.
我正在遵循以下步骤进行操作:
I am kludging my way through with the following:
foreach ($allowed_files as $filename) {
$link_filename = substr(basename($filename), 4, strrpos(basename($filename), '.'));
$src_filename = substr($link_filename, 0, strrpos($link_filename) - 4);
echo $src_filename;
}
...但是,如果扩展字符串长度超过3,则无法使用. 我在PHP文档中环顾四周,无济于事.
...But that can't work if the extension string length is more than 3. I looked around in the PHP docs to no avail.
答
PHP has a handy pathinfo()
function that does the legwork for you here:
foreach ($allowed_files as $filename) {
echo pathinfo($filename, PATHINFO_FILENAME);
}
示例:
$files = array(
'somefile.txt',
'anotherfile.pdf',
'/with/path/hello.properties',
);
foreach ($files as $file) {
$name = pathinfo($file, PATHINFO_FILENAME);
echo "$file => $name\n";
}
输出:
somefile.txt => somefile
anotherfile.pdf => anotherfile
/with/path/hello.properties => hello