truncate / shorten caption for random block

whodah
whodah's picture

Joined: 2003-05-17
Posts: 96
Posted: Sun, 2003-05-18 00:09

some of my captions get rather long and can make the formatting of the page that the random block is on a bit funky.

i saw one post in here to do a simple truncation of a caption for random block.

i took it a bit further: this will truncate the caption to whatever you set $whonumchars to (in my case, 75 characters). but, it'll find the last 'complete word' and truncate it there rather than truncating mid-word.

for instance, if you had:
this picture is nifty

and truncated on the 14th character, you'd get:
this picture i...

this will truncate instead on the 'last complete word' in this case, 'picture' so it would truncate to:
this picture...

i dunno, maybe i'm being a big picky :P

at any rate, it'll also add a 'read more' link to it which simply links to the album that the pic is in.

if you want it, in block-random.php or gallery_random.php replace:

	if ($caption) {
	    $row['content'] .= "<br><center>$caption</center>";
	}

with:

	if ($caption) {
	    /* Who Dah? mofified the next line to only show the first $whonumchars characters */
			/* as some of my photo descriptions can get.. a bit.. long! :>                    */
			$whonumchars = 75;
			if (strlen($caption) > $whonumchars) {
			  $whodah_lastspace = strpos($caption," ");
				if ($whodah_lastspace === false) {
          // no spaces found... don't need to truncate on a 'perfect word'...
					$caption = substr($caption,0,$whonumchars)."... <i><a href=\"".makeAlbumUrl($album->fields["name"])."\">read more</a></i>";
        }
				else {
				  $caption = substr($caption,0,$whonumchars);
					$whoarray = explode(' ', $caption);
          $wholastword = array_pop($whoarray);
          $caption = implode(' ', $whoarray)."... <i><a href=\"".makeAlbumUrl($album->fields["name"])."\">read more</a></i>";
				}
			}
	    $row['content'] .= "<br><center>$caption</center>";
	}

enjoy!
Who Dah? www.whodah.com

 
beckett
beckett's picture

Joined: 2002-08-16
Posts: 3474
Posted: Mon, 2003-05-19 06:09

A regexp might be useful here. I'm thinking something along the lines of:

/^.{75}.*?\b/

So you'd have:

if ($caption) {
   preg_match("/^.{75}.*?\b/", $caption, $newcaption);
   $row['content'] .= "<br><center>$newcaption[0]</center>";
}

Not sure if it's faster, but it's a lot shorter! ;)

-Beckett (

)

 
beckett
beckett's picture

Joined: 2002-08-16
Posts: 3474
Posted: Mon, 2003-05-19 07:05

Oops... mine doesn't have the "read more" link... but you can just test with strlen() to decide whether to print that.