Created
June 21, 2012 13:54
-
-
Save marcosbrasil/2965881 to your computer and use it in GitHub Desktop.
FUnção PHP para limitar texto sem cortar palavras
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function limitarTexto($texto, $limite){ | |
$texto = substr($texto, 0, strrpos(substr($texto, 0, $limite), ' ')) . '...'; | |
return $texto; | |
} | |
// String a ser limitada | |
$string = 'Como limitar caracteres sem cortar as palavras com PHP'; | |
// Mostrando a string limitada em 25 caracteres. | |
print(limitarTexto($string, $limite = 25)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Aproveitando a parte que sobrou
function limitarTexto($texto, $texto2, $limite){
$contador = strlen($texto);
$texto2 = $texto;
if ( $contador >= $limite ) {
$texto = mb_substr($texto, 0, strrpos(mb_substr($texto, 0, $limite), ' '), 'UTF-8') . '...';
$contador2 = strlen($texto);
$resto = $contador - $contador2;
$texto2 = substr($texto2, ($contador2-2), ($resto+1));
return $texto.$texto2;
}
else{
return $texto.$texto2;
}
}
// String a ser limitada
$string = 'Como limitar caracteres sem cortar as palavras com PHP ';
$resultado = (limitarTexto($string, $texto2, $limite = 42));
$partes = explode('...', $resultado);
echo "
resultado = $partes[0]
$partes[1]
";