Created
June 9, 2015 15:46
-
-
Save lorashfuko/4305e43efa686b7f09fa to your computer and use it in GitHub Desktop.
This file contains 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
//*************Обрезаем по символьно**************************************// | |
public static function limitChars($str, $limit = 100, $endChar = NULL, $preserveWords = FALSE) | |
{ | |
$endChar = ($endChar === NULL) ? '…' : $endChar; | |
$limit = (int) $limit; | |
if (trim($str) === '' OR strlen($str) <= $limit) | |
return $str; | |
if ($limit <= 0) | |
return $endChar; | |
if ($preserveWords == FALSE) | |
{ | |
return rtrim(substr($str, 0, $limit)).$endChar; | |
} | |
preg_match('/^.{'.($limit - 1).'}\S*/us', $str, $matches); | |
return rtrim($matches[0]).(strlen($matches[0]) == strlen($str) ? '' : $endChar); | |
} | |
//*************Обрезаем по словам**************************************// | |
public static function limitWords($str, $limit = 100, $endChar = NULL) | |
{ | |
$limit = (int) $limit; | |
$endChar = ($endChar === NULL) ? '…' : $endChar; | |
if (trim($str) === '') | |
return $str; | |
if ($limit <= 0) | |
return $endChar; | |
preg_match('/^\s*+(?:\S++\s*+){1,'.$limit.'}/u', $str, $matches); | |
// Only attach the end character if the matched string is shorter | |
// than the starting string. | |
return rtrim($matches[0]).(strlen($matches[0]) === strlen($str) ? '' : $endChar); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment