Shahriar Kabir
Shahriar Kabir

Reputation: 284

How to show first few lines of a large paragraph?

Please look at the picture:

enter image description here

This is my community forum page. I use at the first row #, Title, Replies & Post Date. Now I want to add another column called Description that will show the first few lines of the whole topic. For example, here the second Title goes as "Components of Computer", but I want show it like "Components of .......". You got the point?

Anyway I store all my data in database. To more assistance here is my code of this page.

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>";
}

Upvotes: 2

Views: 6719

Answers (4)

Manuel
Manuel

Reputation: 11

Try something like this:

<?php 
    $news = strip_tags($row['apal_news']);
    $snews = substr($news,0,50);
    echo $news;
?>

Upvotes: 0

Michael
Michael

Reputation: 920

This function will trim the text without cutting any words if there are spaces. Otherwise it cuts it right off after the length limit.

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;
}

Upvotes: 4

Samuel Cook
Samuel Cook

Reputation: 16828

If your looking for full words this is a simple function that will put "..." if the content is longer than the number of words specified:

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;
}

then you only need to call the function using:

excerpt($row['description'],10)

Upvotes: 4

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

use substr

substr($row['description '], 0, $length_you_want);

Upvotes: 3

Related Questions