Reputation: 79
i have this function to shorten the filename if it is over 23 characters to "...", but i want to keep the files extension
function formatNameFile($nama) {
return strlen($nama) > 23 ? mb_strimwidth($nama, 0, 23, "...") : $nama;
}
echo formatNameFile('resume_t8ffvwnjxibqwhu5l0mk1jwu9mmb4b_3.pdf');
my output
resume_t8ffvwnjxibqw...
expected output
resume_t8ffvwnjxibqw...pdf
how do i achieve this? please help.
Upvotes: 1
Views: 274
Reputation: 1716
You can use this one-liner with pathinfo() and implode() to get the name and extension of the file, truncate the filename to your desired length and then join them back together.
$shorterfilename = implode([substr(pathinfo($filename, PATHINFO_FILENAME), 0, 23), pathinfo($filename, PATHINFO_EXTENSION)], '.');
Upvotes: 0
Reputation: 496
You need to separate handling of filename and file extension.
<?php
function formatNameFile($nama) {
$array = explode('.', $nama);
$extension = end($array);
$newName = strlen($nama) > 23 ? mb_strimwidth($nama, 0, 23, "...") : $nama;
return $newName.$extension;
}
echo formatNameFile('resume_t8ffvwnjxibqwhu5l0mk1jwu9mmb4b_3.pdf');
Upvotes: 4