Return to Snippet

Revision: 46974
at May 28, 2011 06:00 by kendsnyder


Initial Code
<?php

function truncateFilename($filename, $max = 30) {
	if (strlen($filename) <= $max) {
		return $filename;
	}
	if ($max <= 3) {
		return '...';
	}
	if (!preg_match('/^(.+?)(\.[^\.]+)?$/', $filename, $match)) {
		// has newlines or is an empty string
		return $filename;
	}
	list (, $name, $ext) = $match;
	$extLen = strlen($ext);
	$nameMax = $max - ($extLen == 0 ? 3 : $extLen + 2); // 2 for two dots of the elipses
	if ($nameMax <= 1) {
		$truncated = substr($filename, 0, $max - 3) . '...';
	}
	else {
		$truncated = substr($name, 0, $nameMax) . '...' . substr($ext, 1);
	}
	return $truncated;
}

Initial URL


Initial Description


Initial Title
PHP Truncate File Name

Initial Tags


Initial Language
Pascal