1

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?

YeppThat'sMe
  • 1,812
  • 6
  • 29
  • 45
  • possible duplicate of [PHP Get File Name Without File Extension](http://stackoverflow.com/questions/2183486/php-get-file-name-without-file-extension) – Qtax Jan 27 '12 at 13:20
  • You do not need regular expression for this - PHP has built-in features that enable you to do this without regular expressions. – Tadeck Jan 27 '12 at 13:22

5 Answers5

6

Don't use a regex for this - use basename:

$fileName = basename($fullname, ".jpg");
Adam Wright
  • 48,938
  • 12
  • 131
  • 152
4

You can use pathinfo instead of Regex.

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

echo $filename;
Tango Bravo
  • 3,221
  • 3
  • 22
  • 44
2

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.

Matej Baćo
  • 1,312
  • 2
  • 10
  • 12
1

Better answers have already been provided, but here's another alternative!

$fileName = "myfile.jpg";
$name = str_replace(substr($fileName, strpos($fileName,".")), "", $fileName);
IsisCode
  • 2,490
  • 18
  • 20
0

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);
DaveRandom
  • 87,921
  • 11
  • 154
  • 174