rex_formatter::truncate PHP Method

truncate() public static method

Truncates a string.
public static truncate ( string $value, array $format = [] ) : string
$value string Value
$format array Default format is `array('length' => 80, 'etc' => '...', 'break_words' => false)`
return string
    public static function truncate($value, $format = [])
    {
        if (!is_array($format)) {
            $format = [];
        }
        // Max-String-laenge
        if (empty($format['length'])) {
            $format['length'] = 80;
        }
        // ETC
        if (empty($format['etc'])) {
            $format['etc'] = '...';
        }
        // Break-Words?
        if (empty($format['break_words'])) {
            $format['break_words'] = false;
        }
        if (mb_strlen($value) > $format['length']) {
            $format['length'] -= mb_strlen($format['etc']);
            if (!$format['break_words']) {
                $value = preg_replace('/\\s+?(\\S+)?$/', '', substr($value, 0, $format['length'] + 1));
            }
            return substr($value, 0, $format['length']) . $format['etc'];
        }
        return $value;
    }

Usage Example

コード例 #1
0
ファイル: formatter_test.php プロジェクト: staabm/redaxo
 public function testTruncate()
 {
     $value = 'very loooooong text lala';
     $format = ['length' => 10, 'etc' => ' usw.', 'break_words' => true];
     $this->assertEquals('very  usw.', rex_formatter::truncate($value, $format));
     // XXX hmm seems not to be correct
     $format = ['length' => 10, 'etc' => ' usw.', 'break_words' => false];
     $this->assertEquals('very usw.', rex_formatter::truncate($value, $format));
 }