String::tail()

This commit is contained in:
euromark 2012-08-02 13:21:31 +02:00
parent 22c1ac9622
commit 917d912a43
2 changed files with 80 additions and 0 deletions

View file

@ -443,6 +443,46 @@ podeís adquirirla.</span></p>
$this->assertEquals($expected, $result);
}
/**
* testTail method
*
* @return void
*/
public function testTail() {
$text1 = 'The quick brown fox jumps over the lazy dog';
$text2 = 'Heiz&ouml;lr&uuml;cksto&szlig;abd&auml;mpfung';
$text3 = 'El moño está en el lugar correcto. Eso fue lo que dijo la niña, ¿habrá dicho la verdad?';
$text4 = 'Vive la R' . chr(195) . chr(169) . 'publique de France';
$text5 = 'НОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь';
$result = $this->Text->tail($text1, 13);
$this->assertEquals('...e lazy dog', $result);
$result = $this->Text->tail($text1, 13, array('exact' => false));
$this->assertEquals('...lazy dog', $result);
$result = $this->Text->tail($text1, 100);
$this->assertEquals('The quick brown fox jumps over the lazy dog', $result);
$result = $this->Text->tail($text2, 10);
$this->assertEquals('...;mpfung', $result);
$result = $this->Text->tail($text2, 10, array('exact' => false));
$this->assertEquals('...', $result);
$result = $this->Text->tail($text3, 255);
$this->assertEquals($text3, $result);
$result = $this->Text->tail($text3, 21);
$this->assertEquals('...á dicho la verdad?', $result);
$result = $this->Text->tail($text4, 25);
$this->assertEquals('...a R' . chr(195) . chr(169) . 'publique de France', $result);
$result = $this->Text->tail($text5, 10);
$this->assertEquals('...цчшщъыь', $result);
}
/**
* testHighlight method
*

View file

@ -418,6 +418,46 @@ class String {
return preg_replace('|<a\s+[^>]+>|im', '', preg_replace('|<\/a>|im', '', $text));
}
/**
* Truncates text starting from the end.
*
* Cuts a string to the length of $length and replaces the first characters
* with the beginning if the text is longer than length.
*
* ### Options:
*
* - `beginning` Will be used as Beginning and prepended to the trimmed string
* - `exact` If false, $text will not be cut mid-word
*
* @param string $text String to truncate.
* @param integer $length Length of returned string, including ellipsis.
* @param array $options An array of html attributes and options.
* @return string Trimmed string.
*/
public static function tail($text, $length = 100, $options = array()) {
$default = array(
'beginning' => '...', 'exact' => true
);
$options = array_merge($default, $options);
extract($options);
if (!function_exists('mb_strlen')) {
class_exists('Multibyte');
}
if (mb_strlen($text) <= $length) {
return $text;
} else {
$truncate = mb_substr($text, mb_strlen($text) - $length + mb_strlen($beginning));
}
if (!$exact) {
$spacepos = mb_strpos($truncate, ' ');
$truncate = $spacepos === false ? '' : trim(mb_substr($truncate, $spacepos));
}
return $beginning . $truncate;
}
/**
* Truncates text.
*