Monday, November 8, 2010

Replace file extension with PHP

Sometimes we need to read a file from user upload, then save the file in specific file extension after processing, but retain its filename.

Most of the Googled examples assumed that the upload file name adhered to XXXXXX.YYY format, of which a period "." separates file name (XXXXXX) from extension (YYY).

In the event where there are more than one Period "." in the filename, these examples break.

Of course you may use the conventional string function to determine the last Period in the given filename, then strip it with yet a couple of string functions.

One of the way is to use array to achieve the goal, and here is how:

$filenamearray=explode(".",$filename);

array_pop($filenamearray);

array_push($filenamearray,'csv');

$filename=implode(".",$filenamearray);




No comments:

Post a Comment