Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lorashfuko/4305e43efa686b7f09fa to your computer and use it in GitHub Desktop.
Save lorashfuko/4305e43efa686b7f09fa to your computer and use it in GitHub Desktop.
//*************Обрезаем по символьно**************************************//
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) ? '&#8230;' : $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