简体   繁体   中英

Replacing dots in a filename

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

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']);
$str = "file.name.word.jpg";
$regex = "/(\.)(?=\S+\.)/";
echo preg_replace($regex, "_", $str);

short form

echo preg_replace("/(\.)(?=\S+\.)/", "_", "file.name.word.jpg");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM