PDA

View Full Version : How to remove file extension with PHP


tux
02-02-2010, 09:01 PM
Hi all,

How do you go about removing the extension from a file.

For example, I have a file name, lets say, "DSCV1234.jpg".

How would I remove the .jpg so I am left with DSCV1234.

Also, is there a way to remove the letters from the front too so I would be just left with the number 1234.

Thanks.

domedia
02-02-2010, 09:09 PM
Hey tux, why are you doing this?
There might be an easier way.

tux
02-02-2010, 09:49 PM
Hi Domedia,

I'm building a CMS for my photography website to deal with the admin side.

To simplify things I am keeping the image number the same as the file name number so want to remove the extension. This would save manually entering the number for each image and also can be appended to any order number that is created from sales.

It would be better too if I could remove the letters from the front and maybe even replace them with different letters.

Cheers.

edbr
02-03-2010, 01:04 AM
found this example
<?php

// your file
$file = 'image.jpg';

$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);

echo $file_name; // outputs 'image'

?>

edbr
02-03-2010, 01:12 AM
have alook here myou might find something
http://php.net/manual/en/function.substr.php

tux
02-03-2010, 09:57 AM
Thanks for that edbr, simple when you know how mate.

Here is how to do it for the benefit of anyone interested.

This removes the file extension, returning DSCV1234.

$filename = "DSCV1234.jpg";

$result = substr("$filename", 0, -4); // returns "DSCV1234"

echo $result;

...and this removes both the letters and the file extension, returning 1234.


$filename = "DSCV1234.jpg";

$result = substr("$filename", 4, -4); // returns "1234"

echo $result;

You could use this for any string but remember that the string count starts at zero. eg. 0 would equal D, 1 would equal S, etc.

Hope this helps others.

Regards, Paul