Last active
February 16, 2016 11:39
-
-
Save syammohanmp/c81579dcf1f20153cbe8 to your computer and use it in GitHub Desktop.
Word Limit PHP Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Word limit | |
function wordLimit($str, $limit = 100, $end_char = '…') | |
{ | |
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