php如何获取js中的文件路径,如何使用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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值