Skip to content

Instantly share code, notes, and snippets.

@dvapelnik
Forked from dmitrymomot/limit_chars.php
Created July 27, 2014 21:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvapelnik/2ddea13dbda6c842a047 to your computer and use it in GitHub Desktop.
Save dvapelnik/2ddea13dbda6c842a047 to your computer and use it in GitHub Desktop.
<?php
class Text {
/**
* Limits a phrase to a given number of characters.
*
* $text = Text::limit_chars($text);
*
* @param string $str phrase to limit characters of
* @param integer $limit number of characters to limit to
* @param string $end_char end character or entity
* @param boolean $preserve_words enable or disable the preservation of words while limiting
* @return string
*/
public static function limit_chars($str, $limit = 100, $end_char = NULL, $preserve_words = FALSE)
{
$end_char = ($end_char === NULL) ? '…' : $end_char;
$limit = (int) $limit;
if (trim($str) === '' OR mb_strlen($str) <= $limit)
return $str;
if ($limit <= 0)
return $end_char;
if ($preserve_words === FALSE)
return rtrim(mb_substr($str, 0, $limit)).$end_char;
// Don't preserve words. The limit is considered the top limit.
// No strings with a length longer than $limit should be returned.
if ( ! preg_match('/^.{0,'.$limit.'}\s/us', $str, $matches))
return $end_char;
return rtrim($matches[0]).((strlen($matches[0]) === strlen($str)) ? '' : $end_char);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment