Replacing dots in a filename

ε祈祈猫儿з 提交于 2020-02-29 06:35:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!