Forum Moderators: coopster
A small problem
I am working on an article DB. on the first page i show the first 180 char. of each and a link to the hole article. This works fine:
if ((strlen($body) > 180) && (strlen($body) > 1)) { $body = substr("$body", 0, 180)."... ";}
The problem is that the 180 char. limit chops of words. I have tried to take a look at PHP's numeruos string functions but havent been able to make it so that the words are not chopped of. Maybe it is possible to retrieve a set number of words instead of char.
I hope the prob is clear.
Kind regards
/Klaus b
Should work to chop off the end of the string after the last space.
if ((strlen($body) > 180) && (strlen($body) > 1)) {
$whitespaceposition = strpos($body," ",175)-1;
$body = substr($body, 0, $whitespaceposition);
}
Hope it helps
Birdman
function [php.net] truncate($string, $length = '', $replacement = '...', $start = 180) {
if [php.net] (strlen [php.net]($string) <= $start) return [php.net] $string;
if [php.net] ($length) {
return [php.net] substr_replace [php.net]($string, $replacement, $start, $length);
} else [php.net] {
return [php.net] substr_replace [php.net]($string, $replacement, $start);
}
}
// ...and in your processing code...
$body = truncate($body);
Hi - managed to implement your piece of code quite successfully. I've added in a [read more] link back to the complete body of orginal text.
On long strings (I've set mine to 60 characters) it works as intended. However, on shorter strings (less than 60 characters), the code seems to throw in a line break somewhere. This between the end of the truncated text block and the [read more] link. Any ideas on how to may be resolve this?
Not sure if this is actually coming in from the original piece of text as found in the $body item?