简体   繁体   中英

PHP RegEx extract filename

I need your help with a RegEx in PHP

I have something like: vacation.jpg and I am looking for a RegEx which extracts me only the 'vacation' of the filename. Can someone help me?

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

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

You can use pathinfo instead of 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:

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

Approach 2 (better, use pathinfo() ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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