我正在制作一个博客,我想在其中显示主页上所有帖子的摘要,而不是整个帖子。下面是我用来在主页上获取帖子的函数。
function get_content($id = '')
{
if ($id != ""):
$id = mysql_real_escape_string($id);
$sql = "SELECT * from cms_content WHERE id = '$id'";
$return = '<p><a href="http://localhost/www/">Go back to Home page</a></p>';
echo $return;
else:
$sql = "select * from cms_content ORDER BY id DESC";
endif;
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) != 0):
while ($row = mysql_fetch_assoc($res)) {
echo '<h1><a href="index.php?id=' . $row['id'] . '">' . $row['title'] . '</a></h1>';
echo '<p>' . "by: " . $row['author'] . ", posted on: " . $row['date'] . '<p>';
echo '<p>' . $row['body'] . '</p><br />';
}
else:
echo '<p>We are really very sorry, this page does not exist!</p>';
endif;
}然后我简单地使用这段php代码来获取帖子:
<?php
if (isset($_GET['id'])) :
$obj->get_content($_GET['id']);
else :
$obj->get_content();
endif;
?>那么如何仅使用php函数或mysql来获取摘要,因为我知道我们可以使用mysql查询来获取限制的字数?
发布于 2011-09-19 01:32:59
function sumarize($your_string, $limit_lines){
$count = 0;
foreach(explode("\n", $your_string) as $line){
$count++;
echo $line."\n";
if ($count == $limit_lines) break;
}
}
sumarize($row['body'], 10);将显示前十行
发布于 2011-09-19 01:44:38
单行:
echo '<p>'.implode("\n",array_slice(explode("\n",$row['body']),0,10)).'</p>';而不是使用$row['body']行
https://stackoverflow.com/questions/7463153
复制相似问题