PHP: Limit a strings characters

This function will limit the number of words shown if the total character limit is over a certain number and add … after the string. Very useful if you want to trim titles or anywhere where you are limited by space:


function limitCharacters($string){
$count = strlen($string);
// change 50 to the number of characters you want to check for
if($count > 50){
//change 5 to the number of words you want to limit to.
//change ... to anything you want to use to show its clipped
$newstring = implode(' ',array_slice(explode(' ',$string),0,5)).'...';
}else{
$newstring = $string;
}
return $newstring;
}

To call the function simply use:

limitCharacters($mystring);

Leave a Reply