note 84728 modified in function.substr-replace by danbrown

From: Date: Mon, 28 Jul 2008 00:23:17 +0000
Subject: note 84728 modified in function.substr-replace by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-142833@lists.php.net to get a copy of this message
the version of my predecessor will add $rep even if the string is shorter than max. fixed version: <?php function truncate($string, $max = 20, $rep = '') { if (strlen($string) <= ($max + strlen($rep))) { return $string; } $leave = $max - strlen ($rep); return substr_replace($string, $rep, $leave); } ?> To preserve the filename extension you can call it like this: truncate([filename], 30, '...' . end(explode('.', [filename]))) --was-- the version of my predecessor will add $rep even if the string is shorter than max. fixed version: function truncate($string, $max = 20, $rep = '') { if (strlen($string) <= ($max + strlen($rep))) { return $string; } $leave = $max - strlen ($rep); return substr_replace($string, $rep, $leave); } To preserve the filename extension you can call it like this: truncate([filename], 30, '...' . end(explode('.', [filename]))) http://php.net/manual/en/function.substr-replace.php

« previous php.notes (#142833) next »