Skip to content

Instantly share code, notes, and snippets.

@uxjw
Last active August 29, 2015 14:20
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 uxjw/d3cdcc668e649b09a3df to your computer and use it in GitHub Desktop.
Save uxjw/d3cdcc668e649b09a3df to your computer and use it in GitHub Desktop.
Trim a string to a set length of words
<?php
// Shorten a string to a specific word count
function wordTrim($str,$maxwords=25, $more = '...'){
$words = explode(' ',trim($str));
if(count($words) > $maxwords)
{
$newStr = array();
for($i=0;$i<$maxwords;$i++)
$newStr[] = $words[$i];
return implode(' ',$newStr) . $more;
}
else
{
return $str;
}
return (strlen($str) > $maxwords) ? substr($str,0,$maxwords) . $more : $str;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment