Skip to content

Instantly share code, notes, and snippets.

@syammohanmp
Last active February 16, 2016 11:39
Show Gist options
  • Save syammohanmp/c81579dcf1f20153cbe8 to your computer and use it in GitHub Desktop.
Save syammohanmp/c81579dcf1f20153cbe8 to your computer and use it in GitHub Desktop.
Word Limit PHP Function
<?php
// Word limit
function wordLimit($str, $limit = 100, $end_char = '&#8230;')
{
if (trim($str) == '')
return $str;
// always strip tags for text
$str = strip_tags($str);
$find = array("/\r|\n/u", "/\t/u", "/\s\s+/u");
$replace = array(" ", " ", " ");
$str = preg_replace($find, $replace, $str);
preg_match('/\s*(?:\S*\s*){'.(int)$limit.'}/u', $str, $matches);
if (strlen($matches[0]) == strlen($str))
$end_char = '';
return rtrim($matches[0]).$end_char;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment