Cercando in rete mi sono imbattuto in una funzione secondo me molto utile. Permette infatti di prelevare solo una porzione di testo da una stringa (es. tre caratteri), includendo comunque gli eventuali TAG HTML in modo che l’output HTML sia corretto. Ad esempio
1 2 3 |
echo truncate('jo<i><b>n</b>as</i>', 3, '...'); //jo<... echo truncate('jo<i><b>n</b>as</i>', 3, '...', true); //jo<i><b>n</b></i>... echo truncate('jo<i><b>n</b>as</i>', 3, '...', true, false); //jo<i><b>n... |
Segue la funzione:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
"]function truncate($s, $l, $e = '...', $isHTML = false){ $i = 0; $tags = array(); if($isHTML){ preg_match_all('/<[^>]+>([^<]*)/', $s, $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); foreach($m as $o){ if($o[0][1] - $i >= $l) break; $t = substr(strtok($o[0][0], " \t\n\r\0\x0B>"), 1); if($t[0] != '/') $tags[] = $t; elseif(end($tags) == substr($t, 1)) array_pop($tags); $i += $o[1][1] - $o[0][1]; } } return substr($s, 0, $l = min(strlen($s), $l + $i)) . (count($tags = array_reverse($tags)) ? '</' . implode('></', $tags) . '>' : '') . (strlen($s) > $l ? $e : ''); } |
Se hai trovato utili le informazioni su questo blog,
Fai una donazione!
Clicca sul bottone qui sotto o almeno clicca sul banner pubblicitario 🙂
Commenta