¿Hay alguna manera de hacerlo sin escribir mi propia función?Cortar texto sin destruir las etiquetas html
Por ejemplo:
$text = 'Test <span><a>something</a> something else</span>.';
$text = cutText($text, 2, null, 20, true);
//result: Test <span><a>something</a></span>
Necesito hacer esta función indestructible
Mi problema es similar al This thread pero necesito una mejor solución. Me gustaría mantener las etiquetas anidadas intactas.
Hasta ahora mi algoritmo es:
function cutText($content, $max_words, $max_chars, $max_word_len, $html = false) {
$len = strlen($content);
$res = '';
$word_count = 0;
$word_started = false;
$current_word = '';
$current_word_len = 0;
if ($max_chars == null) {
$max_chars = $len;
}
$inHtml = false;
$openedTags = array();
for ($i = 0; $i<$max_chars;$i++) {
if ($content[$i] == '<' && $html) {
$inHtml = true;
}
if ($inHtml) {
$max_chars++;
}
if ($html && !$inHtml) {
if ($content[$i] != ' ' && !$word_started) {
$word_started = true;
$word_count++;
}
$current_word .= $content[$i];
$current_word_len++;
if ($current_word_len == $max_word_len) {
$current_word .= '- ';
}
if (($content[$i] == ' ') && $word_started) {
$word_started = false;
$res .= $current_word;
$current_word = '';
$current_word_len = 0;
if ($word_count == $max_words) {
return $res;
}
}
}
if ($content[$i] == '<' && $html) {
$inHtml = true;
}
}
return $res;
}
Pero, por supuesto, no va a funcionar. Pensé en recordar las etiquetas abiertas y cerrarlas si no estaban cerradas, pero ¿tal vez hay una mejor manera?
@Kaminari - He puesto esta función en un par de pruebas, pero todavía no puede garantizar que funciona en todas las situaciones posibles. – Wh1T3h4Ck5
El problema es que no quiero cortar palabras a la mitad. Necesito hacer un contenido corto y limpio de todo el contenido sin destruir html – Kaminari