[英]PHP: filename without file extension- best way?
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;
}
...But that can't work if the extension string length is more than 3. I looked around in the PHP docs to no avail. ...但是如果扩展字符串长度超过3,则无法工作。我在PHP文档中查看无效。
PHP has a handy pathinfo()
function that does the legwork for you here: PHP有一个方便的pathinfo()
函数,可以在这里为你做腿部工作:
foreach ($allowed_files as $filename) {
echo pathinfo($filename, PATHINFO_FILENAME);
}
Example: 例:
$files = array(
'somefile.txt',
'anotherfile.pdf',
'/with/path/hello.properties',
);
foreach ($files as $file) {
$name = pathinfo($file, PATHINFO_FILENAME);
echo "$file => $name\n";
}
Output: 输出:
somefile.txt => somefile
anotherfile.pdf => anotherfile
/with/path/hello.properties => hello
try this 尝试这个
function file_extension($filename){
$x = explode('.', $filename);
$ext=end($x);
$filenameSansExt=str_replace('.'.$ext,"",$filename);
return array(
"filename"=>$filenameSansExt,
"extension"=>'.'.$ext,
"extension_undotted"=>$ext
);
}
usage: 用法:
$filenames=array("file1.php","file2.inc.php","file3..qwe.e-rt.jpg");
foreach($filenames as $filename){
print_r(file_extension($filename));
echo "\n------\n";
}
output 产量
Array
(
[filename] => file1
[extension] => .php
[extension_undotted] => php
)
------
Array
(
[filename] => file2.inc
[extension] => .php
[extension_undotted] => php
)
------
Array
(
[filename] => file3..qwe.e-rt
[extension] => .jpg
[extension_undotted] => jpg
)
------
list($ file)= explode('。',$ filename);
Try this: 尝试这个:
$noExt = preg_replace("/\\.[^.]*$/", "", $filename);
Edit in response to cletus's comment: 编辑以回应cletus的评论:
You could change it in one of a few ways: 您可以通过以下几种方式之一进行更改:
$noExt = preg_replace("/\\.[^.]*$/", "", basename($filename));
// or
$noExt = preg_replace("/\\.[^.\\\\\\/]*$/", "", $filename);
Yes, PHP needs regex literals... 是的,PHP需要正则表达式文字......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.