Tagliare un articolo
-
Salve ragazzi ho un problema, anzi l'ho sempre avuto, vorrei poter tagliare un testo lungo di un articolo in modo che possa mostrare un anteprima,
ora, il problema non e tanto tagliare il testo in sè, senza troncare le parole, a questo ho i l rimedio, ma vorrei che non lasciasse tags nel testo aperti, che sò uno <strong> o un >em> ecc ecc, potrei usare uno strip_tags(), ma vorrei che tenesse gli accapo, eventuali immagini ad inizio articolo ecc,conoscete un metodo valido?
-
Ciao Khendall,
puoi usare questa classe:class String { public static function truncate($text, $length, $suffix = '…', $isHTML = true){ $i = 0; $tags = array(); if($isHTML){ preg_match_all('/<[^>]+>([^<]*)/', $text, $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); foreach($m as $o){ if($o[0][1] - $i >= $length) 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]; } } $output = substr($text, 0, $length = min(strlen($text), $length + $i)) . (count($tags = array_reverse($tags)) ? '</' . implode('></', $tags) . '>' : ''); // Get everything until last space $one = substr($output, 0, strrpos($output, " ")); // Get the rest $two = substr($output, strrpos($output, " "), (strlen($output) - strrpos($output, " "))); // Extract all tags from the last bit preg_match_all('/<(.*?)>/s', $two, $tags); // Add suffix if needed if (strlen($text) > $length) { $one .= $suffix; } // Re-attach tags $output = $one . implode($tags[0]); return $output; } } -
Ciao! Sembra che tu sia interessato a questa conversazione, ma non hai ancora un account.
Stanco di dover scorrere gli stessi post a ogni visita? Quando registri un account, tornerai sempre esattamente dove eri rimasto e potrai scegliere di essere avvisato delle nuove risposte (tramite email o notifica push). Potrai anche salvare segnalibri e votare i post per mostrare il tuo apprezzamento agli altri membri della comunità.
Con il tuo contributo, questo post potrebbe essere ancora migliore 💗
Registrati Accedi
