Kim
Kim

Reputation: 79

short filename if it's too long but keep the files extension

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

Answers (2)

Chris Wheeler
Chris Wheeler

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

Mai Truong
Mai Truong

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

Related Questions