New class introduced to limit the length of the string
This class can limit the length of a string without cutting words.
It can take a string and return the initial characters if it exceeds a given length limit.
The returned string only includes complete words, so it does not cut the last word in the middle.
It can take a string and return the initial characters if it exceeds a given length limit.
The returned string only includes complete words, so it does not cut the last word in the middle.
Here is the class code
<?php
/*
* String_Delimiter
*
* Limita a quantidade de caracteres numa string, retornando todas as palavras "inteiras"
*
* @author Gabriel (Okatsura) Lau
*/
class String_Delimiter {
/*
* @param integer $limite : Número máximo de caracteres permitidos
* @param string $string: String a ser reduzida
*
* @return string : A string reduzida, caso tenha passado do limite
*/
public function limit($limite = null, $string = null){
$string = $novaString = $this->_fixString($string);
$numCaracteres = $this->_countCaracteres($string);
if($numCaracteres > $limite){
$novaString = $this->_fixString(substr($string, 0, $limite)); //Corta a string para caber no limite
$novoNumPalavras = $this->_countWords($novaString);
$pedacosStringOriginal = explode(" ", $string);
$tamUltimaPalavraCortada = strlen(end(explode(" ", $novaString)));
$tamUltimaPalavraOriginal = strlen($pedacosStringOriginal[$novoNumPalavras-1]);
if($tamUltimaPalavraCortada < $tamUltimaPalavraOriginal){
// Elimina a última palavra se ela estiver imcompleta
$novaString = explode(" ", $novaString);
array_pop($novaString);
$novaString = implode(" ",$novaString);
}
}//end if
return $novaString;
}
private function _countWords($string){
return count(explode(" ", $string));
}
private function _countCaracteres($string){
return strlen($string);
}
private function _fixString($string){
return trim(preg_replace('/ +/', " ", $string));
// Elimina os espaços duplos "em branco" e espaços no início e fim da string
}
}//end class
/*
* Exemplo de uso:
*/
$delimiter = new String_Delimiter();
echo $delimiter->limit(55," Aenean volutpat metus nec arcu pulvinar
consequat. Mauris ac vulputate sapien. Sed vehicula risus et libero pretium
varius nec nec orci. Curabitur vel cursus diam. Nullam nulla orci, commodo eu. ");
?>
No comments:
Post a Comment