Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

Regular expression filename

I have a site where with jQuery/ajax I want to upload my image. The problem is when I have strange filename for my image. Like with dots or other. I have tried with this mode but doesn't work fine, it replace the dot in file extension for example if I have

image.test.png

become

imagetestpng

but I want this:

imagetest.png

This is my code:

$name = $_FILES['upload']['name'];
$size = $_FILES['upload']['size'];
$name = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $name);
echo($name);

How to solve this? Thanks

Upvotes: 0

Views: 91

Answers (2)

Orangepill
Orangepill

Reputation: 24665

You can use this to replace the characters in the filename while preserving the file extension.

$name = preg_replace('/[^a-zA-Z0-9_-]+/',
                     "",
                     pathinfo($name, PATHINFO_FILENAME)
        ) . (pathinfo($name, PATHINFO_EXTENSION)?"." . pathinfo($name, PATHINFO_EXTENSION):"");

Upvotes: 2

Ja͢ck
Ja͢ck

Reputation: 173662

First, you need to decompose the file name:

$info = pathinfo($name);

Then apply your filter on both parts:

$name = preg_replace("/[^\w-]+/", "", $info['filename']);
// check if we have an extension
if (isset($info['extension'])) {
    $name .= '.' . preg_replace('/[^\w]/', '', $info['extension']);
}

Demo

Upvotes: 2

Related Questions