Skip to content

Instantly share code, notes, and snippets.

@jhafner
Created April 30, 2012 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhafner/2563524 to your computer and use it in GitHub Desktop.
Save jhafner/2563524 to your computer and use it in GitHub Desktop.
Limit number of words via PHP
function snippet($text,$length=100,$tail="...") {
$text = strip_tags($text);
$text = trim($text);
$txtl = strlen($text);
if($txtl > $length) {
for($i=1;$text[$length-$i]!=" ";$i++) {
if($i == $length) {
return substr($text,0,$length) . $tail;
}
}
$text = substr($text,0,$length-$i+1) . $tail;
}
return $text;
}
/* Usage: snippet($textSource,100,);
* Note: the length value doesn't seem to correlate to the actual number of words.*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment