Oto funkcja modyfikowany kolejny znalazłem w Internecie; usuwa wszelkie HTML i oczyszcza niektóre funky znaków MS; następnie dodaje do treści opcjonalny znak wielokropka, aby pokazać, że zostało skrócone. Poprawnie dzieli się na słowo, więc nie będziesz miał pozornie przypadkowych znaków;
/**
* Function to ellipse-ify text to a specific length
*
* @param string $text The text to be ellipsified
* @param int $max The maximum number of characters (to the word) that should be allowed
* @param string $append The text to append to $text
* @return string The shortened text
* @author Brenley Dueck
* @link http://www.brenelz.com/blog/2008/12/14/creating-an-ellipsis-in-php/
*/
function ellipsis($text, $max=100, $append='…') {
if (strlen($text) <= $max) return $text;
$replacements = array(
'|<br /><br />|' => ' ',
'| |' => ' ',
'|’|' => '\'',
'|‘|' => '\'',
'|“|' => '"',
'|”|' => '"',
);
$patterns = array_keys($replacements);
$replacements = array_values($replacements);
$text = preg_replace($patterns, $replacements, $text); // convert double newlines to spaces
$text = strip_tags($text); // remove any html. we *only* want text
$out = substr($text, 0, $max);
if (strpos($text, ' ') === false) return $out.$append;
return preg_replace('/(\W)&(\W)/', '$1&$2', (preg_replace('/\W+$/', ' ', preg_replace('/\w+$/', '', $out)))) . $append;
}
Wejście:
<p class="body">The latest grocery news is that the Kroger Co. is testing a new self-checkout technology. My question is: What’s in it for me?</p> <p>Kroger said the system, from Fujitsu,
wyjściowa:
The latest grocery news is that the Kroger Co. is testing a new self-checkout technology. My question is: What's in it for me? Kroger said the …
Co to jest śpiewać? –
* (powiązane) * [Obcięcie łańcucha wielobajtowego na n znaków] (http://stackoverflow.com/questions/2154220/truncate-a-multibyte-string-to-n-chars). Rozwiązanie tam się tnie w odniesieniu do granic słów. To duplikat, jeśli nie interesują cię zdania, ale tylko słowa. – Gordon
możliwy duplikat: http://stackoverflow.com/questions/79960/how-to- truncate-a-string-in-php-to-word-closest-to-a-ertain-number-of-charac – jasonbar