Trimming Strings in PHP

Suppose you have a 10 pixels post header and had a post title “Supercalifragilisticexpialidocious” … the clever monkey in your head will soon realise that you cannot unscrew anything with a rubber hammer. You need a new tool.

Here it is: a function to trim a string and append a little bit extra on the end of it.


function trim($str, $lim, $chr = '…')
{
// If length of string is less than the limit ($lim), return string as is.
if (strlen($str) <= $lim) return $str; //Otherwise, cut string down to the limit's size. //We subtract 3 because we'll be adding a "..." denoted by $chr to the end of the string return (substr($str, 0, $lim - 3))." ".$chr; }

Of course if you want to do this with Arabic you'll run into some problems. You'll need to use PHP's mb_substr which is a multi-byte safe version of substr().

Here's a modified version for a 'utf8' character set (e.g. Arabic):


function trimArabic($str, $lim, $chr = '…')
{
// If length of string is less than $lim, return string
if (strlen($str) <= $lim) return (substr($str, 0, strlen($str))); // Else, cut string down to size return (mb_substr($str, 0, $lim - 3,"utf-8")." ".$chr); }

One Comment on “Trimming Strings in PHP

  1.  by  alex

    Thanks!!!! been bashing my head against that for about an hour.

Leave a Reply

Your email address will not be published. Required fields are marked *