Molto spesso può essere utile o necessario tagliare / troncare un testo per mostrarne solo un certo numero di caratteri a fronte del testo complessivo. Di seguito ecco una breve funzione PHP che farà proprio questo. Se si desidera utilizzarla in un tema WordPress, basta inserirla all’interno nel file functions.php e richiamarla ove desiderato.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/** * Trims a string of words to a specified number of characters, gracefully stopping at white spaces. * Also strips HTML tags, to prevent breaking in the middle of a tag. * @param string $text The string of words to be trimmed. * @param int $length Maximum number of characters; defaults to 45. * @param string $append String to append to end, when trimmed; defaults to ellipsis. * @return String of words trimmed at specified character length. * @author c.bavota */ function trim_characters( $text, $length = 45, $append = '…' ) { $length = (int) $length; $text = trim( strip_tags( $text ) ); if ( strlen( $text ) > $length ) { $text = substr( $text, 0, $length + 1 ); $words = preg_split( "/[s]| /", $text, -1, PREG_SPLIT_NO_EMPTY ); preg_match( "/[s]| /", $text, $lastchar, 0, $length ); if ( empty( $lastchar ) ) array_pop( $words ); $text = implode( ' ', $words ) . $append; } return $text; } |
Nella variabile $length viene specificato il numeri di caratteri dopo i quali il testo verrà troncato (di default 45); la variabile $append specifica i caratteri da visualizzare subito sopo l’interruzione (di default tre punti). Entrambi le variabili potete impostarle a vostro piacimento naturalmente. In tutti i casi l’interruzione avverà al primo spazio presente dopo il numero di caratteri specificato, affinchè si eviti di troncare le parole.
Inserita la funzione basterà solo applicarla alla stringa desiderata:
1 2 |
$string = "This is a string of text that I want to trim down to a specific number of characters."; trim_characters( $string ); // Output: This is a string of text that I want to trim... |