Black
Black

Reputation: 20272

Get file extension with preg_replace

How can I get a file's extension with preg_replace? What is the correct regex to solve this problem?

$test = "picture.jpeg";

$ret = preg_replace("/(\.[\w]+)$/", "$1", $test);
echo $ret;    //expected output: jpeg

Upvotes: 0

Views: 329

Answers (1)

CinCout
CinCout

Reputation: 9619

To get the extension of any file, use this regex:

.*?\.(.*)$

Run it on Regex101

This regex can be used in preg_replace()

EDIT:

Even though the explanation is available at the link, I put the same here on OP's request:

a. .*?lazily matches any character (except newline)
b. \. matches the character . literally
c. (.*)$ everything till the end of the input (represented by $) is then captured in the first capturing group.

Upvotes: 1

Related Questions