【问题标题】:Display post excerpts, limited by word count显示帖子摘录,受字数限制
【发布时间】:2012-01-24 16:05:17
【问题描述】:

我正在我的 php 网站(不是 Wordpress 网站)的主索引上工作,我显示了两个最新帖子。事情在描述上,它显示了我发现自己需要显示帖子摘录的整篇文章,可能有 35 个字的限制。

<?=$line["m_description"]?>

<?
$qresult3 = mysql_query("SELECT * FROM t_users WHERE u_id=".$line["m_userid"]." LIMIT 1");
if (mysql_num_rows($qresult3)<1) { ?>

【问题讨论】:

标签: php truncate


【解决方案1】:
<?php

// just the excerpt
function first_n_words($text, $number_of_words) {
   // Where excerpts are concerned, HTML tends to behave
   // like the proverbial ogre in the china shop, so best to strip that
   $text = strip_tags($text);

   // \w[\w'-]* allows for any word character (a-zA-Z0-9_) and also contractions
   // and hyphenated words like 'range-finder' or "it's"
   // the /s flags means that . matches \n, so this can match multiple lines
   $text = preg_replace("/^\W*((\w[\w'-]*\b\W*){1,$number_of_words}).*/ms", '\\1', $text);

   // strip out newline characters from our excerpt
   return str_replace("\n", "", $text);
}

// excerpt plus link if shortened
function truncate_to_n_words($text, $number_of_words, $url, $readmore = 'read more') {
   $text = strip_tags($text);
   $excerpt = first_n_words($text, $number_of_words);
   // we can't just look at the length or try == because we strip carriage returns
   if( str_word_count($text) !== str_word_count($excerpt) ) {
      $excerpt .= '... <a href="'.$url.'">'.$readmore.'</a>';
   }
   return $excerpt;
}

$src = <<<EOF
   <b>My cool story</b>
   <p>Here it is. It's really cool. I like it. I like lots of stuff.</p>
   <p>I also like to read and write and carry on forever</p>
EOF;

echo first_n_words($src, 10);

echo "\n\n-----------------------------\n\n";

echo truncate_to_n_words($src, 10, 'http://www.google.com');

编辑:添加功能示例并说明文本中的标点符号和数字

【讨论】:

    【解决方案2】:

    我有一个函数,虽然其他人可能会说它不好,因为我仍然擅长 PHP(提示欢迎人们)但这会给你你正在寻找的东西,如果有人有建议,它可能需要更好的编码。

    function Short($text, $length, $url, $more){
    $short = mb_substr($text, 0, $length);
    
    if($short != $text) {
        $lastspace = strrpos($short, ' ');
        $short = substr($short , 0, $lastspace);
    
        if(!$more){
            $more = "Read Full Post";
        } // end if more is blank
    
        $short .= "...[<a href='$url'>$more</a>]";
    } // end if content != short
    
    $short = str_replace("’","'", $short);
    $short = stripslashes($short);
    $short = nl2br($short);
    
    } // end short function
    

    使用方法:

    说你的文章内容是变量$content

    function($content, "35", "http://domain.com/article_post", "Read Full Story");
    echo $short;
    

    同样,您可以调整函数以从中删除 $url 和 $more ,并在末尾加上 ... 的摘录。

    【讨论】:

    • @bowlerae 这看起来是一个很好的起点。如果您想清理这种时髦的 windows 字符(连字符、智能/双引号、破折号、复制符号等),除了单引号之外,还有更多符号需要考虑,但这本身就是一个完整的主题。此外,摘录几乎总是遇到最终被截断的 html 的问题。也解决! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    相关资源
    最近更新 更多