Skip to content

Instantly share code, notes, and snippets.

@krciga22
Created January 13, 2013 19:19
Show Gist options
  • Save krciga22/4525755 to your computer and use it in GitHub Desktop.
Save krciga22/4525755 to your computer and use it in GitHub Desktop.
Truncate String PHP Snippet: truncate a string in PHP either by setting a maximum length or maximum number of words. Also includes the ability to append a suffix if the string is truncated.
<?PHP
function truncate($text, $suffix="...",$maxLength=false,$maxWords=false){
$text = trim($text);
$text = preg_replace("/[\s]+/", " ", $text); // convert all consecuritve spaces to single spaces
if($maxLength!==false){
if(strlen($text)>$maxLength){
$text = substr($text, 0, $maxLength).$suffix;
}
}
if($maxWords!==false){
$textArray = explode(' ', $text);
if(count($textArray)>$maxWords){
$textArray = array_splice($textArray, 0, $maxWords);
$text = implode(' ', $textArray).$suffix;
}
}
return($text);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment