简体   繁体   English

PHP RegEx提取文件名

[英]PHP RegEx extract filename

I need your help with a RegEx in PHP 我需要您的PHP正则表达式帮助

I have something like: vacation.jpg and I am looking for a RegEx which extracts me only the 'vacation' of the filename. 我有一个类似的东西:Vacation.jpg,我正在寻找一个RegEx,它仅提取文件名的“假期”。 Can someone help me? 有人能帮我吗?

不要为此使用正则表达式-使用basename

$fileName = basename($fullname, ".jpg");

You can use pathinfo instead of Regex. 您可以使用pathinfo代替Regex。

$file = 'vacation.jpg';
$path_parts = pathinfo($file);
$filename = $path_parts['filename'];

echo $filename;

And if you really need regex, this one will do it: 如果您确实需要正则表达式,那么可以使用它:

$success = preg_match('~([\w\d-_]+)\.[\w\d]{1,4}~i', $original_string, $matches);

Inside matches you will have first part of file name. 内部比赛中,您将拥有文件名的第一部分。

Better answers have already been provided, but here's another alternative! 已经提供了更好的答案,但这是另一种选择!

$fileName = "myfile.jpg";
$name = str_replace(substr($fileName, strpos($fileName,".")), "", $fileName);

You don't need regex for this. 您不需要正则表达式。

Approach 1: 方法1:

$str = 'vacation.jpg';
$parts = explode('.', basename($str));
if (count($parts) > 1) array_pop($parts);
$filename = implode('.', $parts);

Approach 2 (better, use pathinfo() ): 方法2(最好使用pathinfo() ):

$str = 'vacation.jpg';
$filename = pathinfo($str, PATHINFO_FILENAME);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM