Ecco una funzione modificata da un altro che ho trovato on-line; toglie qualsiasi HTML e pulisce alcuni caratteri MS funky prima; aggiunge quindi un carattere di ellissi facoltativo al contenuto per mostrare che è stato abbreviato. Si divide correttamente in una parola, quindi non avrai caratteri apparentemente casuali;
/**
* 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;
}
ingresso:
<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,
uscita:
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 …
fonte
2011-01-14 14:29:39
quello che è un cantare? –
* (correlato) * [Troncare una stringa multibyte su n caratteri] (http://stackoverflow.com/questions/2154220/truncate-a-multibyte-string-to-n-chars). La soluzione lì taglia rispetto ai confini delle parole. È un duplicato se non ti preoccupi delle frasi ma solo delle parole. – Gordon
possibile duplicato: http://stackoverflow.com/questions/79960/how-to-truncate-a-string-in-php-to-the-word-closest-to-a-certain-number-of-charac – jasonbar