Hola,
tengo la siguiente funcion para cortar texto a x cantidad de caracteres:
Código PHP:
Ver original/**
* funcion para cortar texto a la x cantidad de caracteres
* @param <string> $text
* @param <integer> $length
* @param <string> $ending
* @param <boolean> $exact
* @param <boolean> $considerHtml
* @return <string>
*/
public function cortarTexto($text, $length = 100, $ending = "...", $exact = true, $considerHtml = false) {
}
if ($considerHtml) {
return $text;
}
$truncate = "";
preg_match_all("/(<\/?([\w+]+)[^>]*>)?([^<>]*)/", $text, $tags, PREG_SET_ORDER
); foreach ($tags as $tag) {
if (!preg_match("/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s", $tag[2])) { } else if (preg_match("/<\/([\w]+)[^>]*>/s", $tag[0], $closeTag)) { if ($pos !== false) {
}
}
}
$truncate .= $tag[1];
$contentLength = mb_strlen(preg_replace("/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i", " ", $tag[3])); if ($contentLength + $totalLength > $length) {
$left = $length - $totalLength;
$entitiesLength = 0;
if (preg_match_all("/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i", $tag[3], $entities, PREG_OFFSET_CAPTURE
)) { foreach ($entities[0] as $entity) {
if ($entity[1] + 1 - $entitiesLength <= $left) {
$left--;
} else {
break;
}
}
}
$truncate .= mb_substr($tag[3], 0 , $left + $entitiesLength); break;
} else {
$truncate .= $tag[3];
$totalLength += $contentLength;
}
if ($totalLength >= $length) {
break;
}
}
} else {
return $text;
} else {
}
}
if (!$exact) {
if ($considerHtml) {
preg_match_all("/<\/([a-z]+)>/", $bits, $droppedTags, PREG_SET_ORDER
); if (!empty($droppedTags)) { foreach ($droppedTags as $closingTag) {
if (!in_array($closingTag[1], $openTags)) { }
}
}
}
$truncate = mb_substr($truncate, 0, $spacepos); }
}
$truncate .= $ending;
if ($considerHtml) {
foreach ($openTags as $tag) {
$truncate .= "";
}
}
return $truncate;
}
La misma funciona de maravilla salvo por un pequeño inconveniente no me cierra correctamente los tags html. Es decir si yo tengo el texto:
Cita: <p><strong><em>Esto es una prueba para que ver como funciona</em></strong></p>
y ejecuto la funciona asi:
Código PHP:
Ver originalecho cortarTexto($cadena,10,'..',true,true);
me devuelve:
Cita: <p><strong><em>Esto es una...
en vez de:
Cita: <p><strong><em>Esto es una...</p></strong></em>
en que le estoy errando?