选择语言 :

 Core_Text::limit_chars

Limits a phrase to a given number of characters.

$text = Text::limit_chars($text);

string Core_Text::limit_chars( string $str [, integer $limit = integer 100 , string $end_char = null , boolean $preserve_words = bool false ] )
uses
UTF8::strlen

参数列表

参数 类型 描述 默认值
$str string Phrase to limit characters of
$limit integer Number of characters to limit to integer 100
$end_char string End character or entity null
$preserve_words boolean Enable or disable the preservation of words while limiting bool false
返回值
  • string
File: ./core/classes/text.class.php
public static function limit_chars($str, $limit = 100, $end_char = NULL, $preserve_words = FALSE)
{
    $end_char = (null===$end_char) ? '…' : $end_char;

    $limit = (int)$limit;

    if (trim($str) === '' || UTF8::strlen($str) <= $limit)return $str;

    if ($limit <= 0)return $end_char;

    if (false===$preserve_words)return rtrim(UTF8::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);
}