-
-
Save dvapelnik/2ddea13dbda6c842a047 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
<?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