Reputation: 1055
I found this function to create an excerpt for long text. I use this method to manage also accents like è é à ò ì ù ....
function excerpt($string, $lenght = 50, $popover = false, $ellipsed = false) {
if ( $ellipsed ) {
$ellipse = "...";
if ( $popover )
$ellipse = '<span title="More info" data-toggle="popover" data-trigger="hover" data-content="' . $string . '">...</span>';
} else {
$ellipse = "";
}
$boundaryPos = mb_strrpos(mb_substr($string, 0, mb_strpos($string, ' ', $lenght)), ' ');
return mb_substr($string, 0, $boundaryPos === false ? $lenght : $boundaryPos) . $ellipse;
}
Some tests:
echo excerpt("Il treno è partito", 11);
//RETURN Il treno è
echo excerpt("Il treno è partito", 15);
//RETURN Il treno è part
echo excerpt("Il treno è partito", 20);
//RETURN WARNING mb_strpos(): Offset not contained in string
How can I fix error for the last test?
Upvotes: 2
Views: 1296
Reputation: 144
You need to check if the length of the string is less than your length parameter because you can't find 20-th offset of the string, which has length of 19.
P.S. You also have a typo in your length parameter of the excerpt function.
function excerpt($string, $length = 50, $popover = false, $ellipsed = false) {
if ( $ellipsed ) {
$ellipse = "...";
if ( $popover )
$ellipse = '<span title="More info" data-toggle="popover" data-trigger="hover" data-content="' . $string . '">...</span>';
} else {
$ellipse = "";
}
if ( strlen($string) < $length ) {
return $string . $ellipse;
}
$boundaryPos = mb_strrpos(mb_substr($string, 0, mb_strpos($string, ' ', $length)), ' ');
return mb_substr($string, 0, $boundaryPos === false ? $length : $boundaryPos) . $ellipse;
}
echo excerpt("Il treno è partito", 11);
echo excerpt("Il treno è partito", 20);
Upvotes: 1