JBZoo\Utils\Str::truncateSafe PHP 메소드

truncateSafe() 공개 정적인 메소드

Truncate a string to a specified length without cutting a word off.
public static truncateSafe ( string $string, integer $length, string $append = '...' ) : string
$string string The string to truncate
$length integer The length to truncate the string to
$append string Text to append to the string IF it gets truncated, defaults to '...'
리턴 string
    public static function truncateSafe($string, $length, $append = '...')
    {
        $result = self::sub($string, 0, $length);
        $lastSpace = self::rpos($result, ' ');
        if ($lastSpace !== false && $string != $result) {
            $result = self::sub($result, 0, $lastSpace);
        }
        if ($result != $string) {
            $result .= $append;
        }
        return $result;
    }

Usage Example

예제 #1
0
파일: StringTest.php 프로젝트: jbzoo/utils
 public function testTruncateSafe()
 {
     is('The quick brown fox...', Str::truncateSafe('The quick brown fox jumps over the lazy dog', 24));
     is('The quick brown fox jumps over the lazy dog', Str::truncateSafe('The quick brown fox jumps over the lazy dog', 55));
     is('Th...', Str::truncateSafe('The quick brown fox jumps over the lazy dog', 2));
     is('The...', Str::truncateSafe('The quick brown fox jumps over the lazy dog', 3));
     is('The...', Str::truncateSafe('The quick brown fox jumps over the lazy dog', 7));
 }