0

I've got array list:

$myarray = array(
    array(
        'name' => 'File name 1 - type.zip',
        'size' => '600KB',
    ),
    array(
        'name' => 'File name 2 - type.pdf',
        'size' => '1.5MB',
    ),
    array(
        'name' => 'File name 3 - type.jpeg',
        'size' => '50.5KB',
    ),
);

. . . and need to truncate the file names, but keep extensions and size of files.

So for example 'File name 1 - type.zip' should be displayed as 'File name 1 - ... .zip (600KB)'.

Any tips?

talemyn
  • 7,822
  • 4
  • 31
  • 52
Marek S.
  • 13
  • 3
  • just do string substring and grab last 25 characters or however many you want. – Dimi Feb 09 '17 at 19:47
  • 1
    Welcome to Stack Overflow! I updated your question and title to make it match what you are trying to do a little closer, which will make it more likely for you to get an answer that can help you and others. Feel free to clarify more, if you think I have misrepresented your issue. Good luck! – talemyn Feb 09 '17 at 19:47

3 Answers3

0

You could use explode and substr assuming that your len_you_neen is 6 char

$tmpArray = explode('.',$myArray['name']);
$myStr = substr($tmpArray[0], 0, 6);

$resultStr = $myStr . '.'.$tmpArray[1];
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

You can give something like below a try. It doesn't include the filesize but I'm sure you can take it from there.

$fileName = "File name 1 - type.zip";
echo shortenFileNameWhileMaintainingExtension($fileName);

function shortenFileNameWhileMaintainingExtension($fileName, $shortenToLength = 20) {
    $extension = substr(strrchr($fileName, '.'), 1);
    if((strlen($fileName) - strlen($extension)) < $shortenToLength) {
        return $fileName;
    }
    $newFileName = trim(substr($fileName, 0, $shortenToLength)) . "...." . $extension;
    return $newFileName;
}
Aaron W.
  • 9,254
  • 2
  • 34
  • 45
0

You can use pathinfo to separate the name from the extension. Then there are various ways to shorten and add the ellipsis. The method from this answer is very straightforward. You can map this method over your array to format all of the items.

$max = 11;

$formatted = array_map(function($file) use ($max) {
    $info = pathinfo($file['name']);
    $name = $info['filename'];
    $name = strlen($name) > $max ? substr($name, 0, $max) . '...' : $name;
    return "$name$info[extension] $file[size]";
}, $myarray);
Community
  • 1
  • 1
Don't Panic
  • 41,125
  • 10
  • 61
  • 80