当前位置: 动力学知识库 > 问答 > 编程问答 >

php - How to limit the display of content from a database?

问题描述:

I am using the following code to display the title and body content of articles from a database. How can I make only the first 200 characters from the article's body appear as opposed to all the characters?

<?php

$select = mysql_query("SELECT * FROM articles ORDER BY id DESC");

while ($result = mysql_fetch_assoc($select))

{

$id = $result['id'];

$title = $result['title'];

$body = $result['body'];

echo "<h2><a name='$id'>" . $title . "</a></h2>";

echo $body . "<br />";

}

?>

Any help is greatly appreciated!

网友答案:

Change this line:

echo $body . "<br />";

To this:

echo (strlen($body) > 200) ? substr($body,0,200) : $body;
echo "<br />";

That utilizes the comparison operator (aka the ternary operator) to output only the first 200 characters if $body is over 200 chars in length, and the whole body otherwise.

A common technique you could use to mark a truncated block of text would be to add an ellipsis on the end of a truncated text block (three periods, or the HTML entity &hellip;). This is why I usually use the comparison operator here rather than just doing a substr($str,0,200), which would work for both cases, but not let you modify them separately.

网友答案:

substr($body, 0, 200)

Beware if you're storing markup in the database as this may chop a tag in half.

网友答案:

You can do this in PHP as the others have mentioned, or directly in your query as well (if you don't need all of the data on your page):

$select = mysql_query("SELECT id, title, SUBSTR(body, 0, 200) FROM articles ORDER BY id DESC"
网友答案:

I've created a function called limit. Maybe it will be useful for you as well.

function limit($string, $limit) {
        if (strlen($string) < $limit) {
            $result = substr($string, 0, $limit);
        }
        else
            $result =  substr($string, 0, $limit) . '...';
        return $result;
    }


echo limit('Testing my function', 5);

//Output
Test...
分享给朋友:
您可能感兴趣的文章:
随机阅读: