News:

SMF 2.1.6 has been released! Take it for a spin! Read more.

Main Menu

Improved word truncate for ssi_boardNews in SSI.php

Started by Ignatius, July 27, 2004, 05:28:41 AM

Previous topic - Next topic

Ignatius

Here's a small modification I made to SSI.php.
The reason is, that I want my news, which are displayed via SSI.php on the fron page, to be cut after n characters.  The original code in SSI.php does this by simply truncating the text after hte last space before n characters of the nes text, but it doesn't take any UBB tags into account. So if you news text is

[ center]Hello World[/center]

and you tell SSI.php to truncate the news after 12 characters, you will get

Hello

as the result. My improved word-truncate function takes care not to truncate within UBB-Tag blocks, and it trancates at the first space, new line or start/end of a UBB tag.


// function truncateAtWordbound($line, $col) {
if (strlen($line) <= $col) {
return $line;
}
$tag   = 0;
$intag = false;
$count = 0;
for ($i=0; $i<strlen($line); $i++) {
if ($line[$i] == '[') {
$intag = true;
if ($line[$i+1] == '/') {
$tag--;
} else {
$tag++;
}
} elseif ($line[$i] == ']') {
$intag = false;
} elseif ($intag == false) {
$count++;
}
if ($count >= $col && $intag == false && $tag == 0) {
    if ($line[$i] == ' ' || $line[$i] == "\n" || $line[$i] == '[' || $line[$i] == ']') {
if ($line[$i] == ']') {
return substr($line,0,$i+1);
} else {
return substr($line,0,$i);
}
}
}
}
return $line;
}


to call this function you have to replace the lines


            $row['body'] = substr($row['body'], 0, $length);
            $cutoff = strrpos($row['body'], ' ');
            if ($cutoff !== false)
                $row['body'] = substr($row['body'], 0, $cutoff);
            $row['body'] .= '...';


in function ssi_boardNews with these lines


if (strlen($row['body']) > $length) {
$row['body'] = truncateAtWordbound($row['body'],$length);
$row['body'] .= '...';
}


ciao.. Iggi

dobomode

Thank you!! That worked great for me.

Just a small correction though. You need to replace this:


            $row['body'] = substr($row['body'], 0, $length);
            $cutoff = strrpos($row['body'], ' ');
            if ($cutoff !== false)
                $row['body'] = substr($row['body'], 0, $cutoff);
            $row['body'] .= '...';


with this:


$row['body'] = truncateAtWordbound($row['body'],$length);
$row['body'] .= '...';



Advertisement: