PHP Truncate File Name


/ Published in: Pascal
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function truncateFilename($filename, $max = 30) {
  4. if (strlen($filename) <= $max) {
  5. return $filename;
  6. }
  7. if ($max <= 3) {
  8. return '...';
  9. }
  10. if (!preg_match('/^(.+?)(\.[^\.]+)?$/', $filename, $match)) {
  11. // has newlines or is an empty string
  12. return $filename;
  13. }
  14. list (, $name, $ext) = $match;
  15. $extLen = strlen($ext);
  16. $nameMax = $max - ($extLen == 0 ? 3 : $extLen + 2); // 2 for two dots of the elipses
  17. if ($nameMax <= 1) {
  18. $truncated = substr($filename, 0, $max - 3) . '...';
  19. }
  20. else {
  21. $truncated = substr($name, 0, $nameMax) . '...' . substr($ext, 1);
  22. }
  23. return $truncated;
  24. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.