个性化阅读
专注于IT技术分析

如何使用javascript和php从文件路径中检索扩展名和文件名

本文概述

检索带有扩展名的文件名

Java脚本

要检索文件名, 我们将以斜杠/分隔。要使用Javascript实现此目的, 我们将使用以下正则表达式/^.*[\\\/]/:

// Any filepath, even inverted slash
// var filepath = "\\myfilepath\\extensions\\filename.png";
var filepath = "/myfilepath/extensions/filename.png";

// Use the regular expression to replace the non-matching content with a blank space
var filenameWithExtension = filepath.replace(/^.*[\\\/]/, '');

// outputs filename.png
console.log(filenameWithExtension);

正则表达式将从最后一个/(斜杠字符)返回其余文本。由于不是任何文件都可以在其名称中包含/, 但\也可以包含\, 因此此功能适用于所有情况。

如果由于要确保提供的文件路径仅使用已定义的斜杠类型(/或\)而不想使用正则表达式, 则可以将字符串除以指定的字符, 然后获取最后一个项目:

var filepath = "/myfilepath/extensions/filename.png";

// With a normal slash
var group = filepath.split("/");
// or a path with an inverted slash
// var group = filepath.split("\\");

// Use the regular expression to replace the non-matching content with a blank space
var filenameWithExtension = group.pop();
// Or if you can't use pop()
// var filenameWithExtension = group[group.length - 1];

// outputs filename.png
console.log(filenameWithExtension);

的PHP

对于PHP, 我们将使用在所有php版本中都可用的basename函数:

$filepath = "/myfilepath/extensions/filename.jpg";
$filename = basename($filepath); // filename.jpg

注意:处理亚洲字符时, 基名存在一个已知的错误, 为避免这种情况, 你可以使用正则表达式和preg_replace代替:

$filepath = "/myfilepath/extensions/filename.jpg";
$filename = preg_replace('/^.+[\\\\\\/]/', '', $filepath);  // filename.jpg

检索文件扩展名

Java脚本

要使用Javascript从路径(或文件名, 在这种情况下没有关系)中检索扩展名, 我们将用分割字符串。字符, 我们将检索获得的数组的最后一项。

var path = "path/a-long/path/to-my/file.jpg";
var path_splitted = path.split('.');
var extension = path_splitted.pop();

// Here the file will not have extension !
if(extension === path){
  // The filepath doesn't have . characters, that means doesn't have extension. for example :
  // if you try with : path/to/my/file/thisisafile
  // extension == path/to/my/file/thisisafile
}

// show extension
console.log(extension);

的PHP

要使用php从路径中检索扩展名, 我们将使用pathinfo函数。

$path = "this-is-my/long/filepath/to/file.txt";
$ext = pathinfo($path, PATHINFO_EXTENSION);// PATHINFO_EXTENSION is a constant
echo $ext; // output txt

注意:如果你的环境中没有pathinfo函数, 请改用end函数。

$path = "this-is-another-long-path/to/my/file.txt";
$array_ofpath = explode('.', $path);//explode returns an array
$extension = end($array);
赞(0)
未经允许不得转载:srcmini » 如何使用javascript和php从文件路径中检索扩展名和文件名

评论 抢沙发

评论前必须登录!