问题
How should I replace dots with underlines without losing the file extension?
$str = $_FILES['files']['name']; //file.name.word.jpg
$ext = end(explode('.', $str));
$filename = explode('.', $str);
//output file_name_word.jpg
ps: it needs to be before upload.. if the user uploads a file with dots it must to be renamed and inserted on db
回答1:
Use pathinfo() to extract the file name and str_replace() to remove all the dots out of it.
$filename = pathinfo('/path/to/your/file');
echo str_replace('.', '_', $filename['filename']);
回答2:
$str = "file.name.word.jpg";
$regex = "/(\.)(?=\S+\.)/";
echo preg_replace($regex, "_", $str);
short form
echo preg_replace("/(\.)(?=\S+\.)/", "_", "file.name.word.jpg");
来源:https://stackoverflow.com/questions/17689465/replacing-dots-in-a-filename