Re: New frontpage index mod!
MattF wrote:The only problem with truncation is that it screws the W3C compliance if it happens to trim the message inbetween a pair of tags.
Actually, this is true but soonotes (tinytim) managed to resolve this issue with his User Blogs.
Yeah, had to do some searching to get that to work as the function for it is beyond my abilities. I would love to give proper credit for the functions below but I lost that info and have not been able to find it again.
Here's the code from blog.php where I call the function
//First we parse the message
$pre = parse_message($cur_blog['blog'], $cur_blog['hide_smilies']);
// Now we trim it
$str = truncate ($pre, $id);
$pre parses the message normal pun style (ie $cur_post) and then the truncate function is called.
The message and the blog id are required due to the fact the function also adds a 'read more' link.
Below are two functions actually. The truncate function does just that. The close tags function closes any open tags and is fully xhtml 1.0 compliant (ie. it accounts for self closing tags like img)
You should be able to use this without much trouble for what you want to do.
If you look at the truncate function you'll notice $len which sets the amount of characters to display. You will probably want to hard code that. (ie. $len = 400;)
The other variable you need to adjust is $append which adds the read more link.
Hope that helps.
//
// Close any open tags when truncating a blog
//
function close_tags($string)
{
// match opened tags
if(preg_match_all('/<([a-z\:\-]+)[ >]/', $string, $start_tags))
{
$start_tags = $start_tags[1];
// match closed tags
if(preg_match_all('/<\/>([a-z]+)>/', $string, $end_tags))
{
$complete_tags = array();
$end_tags = $end_tags[1];
foreach($start_tags as $key => $val)
{
$posb = array_search($val, $end_tags);
if(is_integer($posb))
{
unset($end_tags[$posb]);
}
else
{
$complete_tags[] = $val;
}
}
}
else
{
$complete_tags = $start_tags;
}
$complete_tags = array_reverse($complete_tags);
for($i = 0; $i < count($complete_tags); $i++)
{
$string .= '</' . $complete_tags[$i] . '>';
}
}
// Removes the </img> tag
$xhtml_tags = array("</img>", "</hr>", "</br>");
$string = str_replace($xhtml_tags, "", $string);
return $string;
}
//
// Truncate string longer than max length
//
function truncate($str, $id) {
global $pun_config;
$len = $pun_config['b_blog_trun_length'];
$splitter = '<!--MORE-->';
$append = ' ... <span class="barlink"><i><a href="blog.php?cid='.$id.'&c_id='.$id.'">Full Blog';
if(strlen($str) <= $len){
return $str;
}
if($len > 0 && !strstr($str,$splitter)){
preg_match('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$len.',}\b#U', $str,$matches);
$str = $matches[0];
# remove trailing opener tags and close all other open tags:
$str = close_tags(preg_replace('#\s*<[^>]+>?\s*$#','',$str).$append);
} else {
$arr = explode($splitter,$str,2);
$str = $arr[0];
}
return $str;
}