Skip to content

Instantly share code, notes, and snippets.

@syammohanmp
Last active February 16, 2016 11:38
Show Gist options
  • Save syammohanmp/e7a7832c031ec06362b9 to your computer and use it in GitHub Desktop.
Save syammohanmp/e7a7832c031ec06362b9 to your computer and use it in GitHub Desktop.
Character Limit PHP Function
<?php
// Character limit
function characterLimit($str, $limit = 150, $end_char = '...')
{
if (trim($str) == '')
return $str;
// always strip tags for text
$str = strip_tags(trim($str));
$find = array("/\r|\n/u", "/\t/u", "/\s\s+/u");
$replace = array(" ", " ", " ");
$str = preg_replace($find, $replace, $str);
if (strlen($str) > $limit)
{
$str = substr($str, 0, $limit);
return rtrim($str).$end_char;
}
else
{
return $str;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment