首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何显示一个大段落的前几行?

如何显示一个大段落的前几行?
EN

Stack Overflow用户
提问于 2012-12-27 12:30:25
回答 4查看 6.1K关注 0票数 2

请看下图:

这是我的社区论坛页面。我在第一行使用#,标题,回复和发布日期。现在,我想添加另一个名为Description的列,它将显示整个主题的前几行。例如,这里的第二个标题是"Components of Computer",但我希望将其显示为"Components of .......“。你明白了吗?

不管怎样,我把我所有的数据都存储在数据库里。要获得更多帮助,这里是我在此页面的代码。

代码语言:javascript
复制
echo "<table border='0' width='100%' id='table-3'>
<tr><td>#</td><td>Title</td><td>Replies</td><td>Post Date</td></tr>";
$sql = mysql_query("SELECT * FROM topics ORDER BY id DESC");
while ($row = mysql_fetch_array($sql)) {
    $replies = mysql_num_rows(mysql_query("SELECT * FROM replies WHERE
               topic_id='" . $row['id'] . "'"));
    echo "<tr><td>" . $row['id'] . "</td><td><a href='show_topic.php?id=" . $row['id']                                                                                          
          . "'> <b>" . $row['title'] . "</b></a></td><td>" . $replies . "</td><td>" .  
          date("d M Y", $row['date']) . "  </td></tr>";
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-12-27 12:33:07

使用substr

代码语言:javascript
复制
substr($row['description '], 0, $length_you_want);
票数 3
EN

Stack Overflow用户

发布于 2012-12-27 12:39:16

如果您正在查找完整的单词,这是一个简单的函数,它将把"...“如果内容长度超过指定的字数:

代码语言:javascript
复制
function excerpt($content,$numberOfWords = 10){     
    $contentWords = substr_count($content," ") + 1;
    $words = explode(" ",$content,($numberOfWords+1));
    if( $contentWords > $numberOfWords ){
        $words[count($words) - 1] = '...';
    }
    $excerpt = join(" ",$words);
    return $excerpt;
}

然后,您只需使用以下命令调用该函数:

代码语言:javascript
复制
excerpt($row['description'],10)
票数 4
EN

Stack Overflow用户

发布于 2012-12-27 12:47:57

如果有空格,此函数将在不剪切任何单词的情况下裁剪文本。否则,它会在长度限制后立即将其截断。

代码语言:javascript
复制
function trim_text($input, $length, $ellipses = true)
{
    if (strlen($input) <= $length) {
        return $input;
    }

    // find last space within length
    $last_space = strrpos(substr($input, 0, $length), ' ');
    if ($last_space === FALSE) {
        $last_space = $length;
    }

    $trimmed_text = substr($input, 0, $last_space);

    // add ellipses
    if ($ellipses) {
        $trimmed_text .= '...';
    }

    return $trimmed_text;
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14049370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档