Jump to content

help displaying first 10 words in database field


kaiman

Recommended Posts

I have the following script to display a brief news clip/description on the homepage of a website. I am trying to get it to display the first ten words from the 'text' field, but it just seems to ignore it and display the whole news item, no errors or anything...

 

Any ideas what's going on or what I am missing?

 

Thanks,

 

kaiman

 

<?php
// connects to server and selects database.
include ("dbconnect.inc.php");

// table name
$tbl_name="news";

// select info from database
$sql="SELECT * FROM $tbl_name ORDER BY id DESC LIMIT 1";
$result=mysql_query($sql);

// display news items
while ($row=mysql_fetch_array($result)){
echo "<h1>Latest News</h1>\n";
$row_date = strtotime($row['date']);
echo "<h3>".date('F, j, Y', $row_date)."</h3>\n";


// cut news paragraph to ten words
if (strlen($row['text']) > 10){
$description = substr($row['text'], 0, 10);
}
else{
$description = $row['text'];
}

echo "<p>".$row['text']."... <a href=\"http://www.mysite.com/news/\">Read more</a></p>\n";
}
?>

SOLVED

 

Thanks for the reply,

 

I actually realized after I posted and re-looked at the PHP substr page that it was based on characters not words, so I just simplified the variable to this and now it works as expected.

 

// cut news to 110 characters and then display
$headline = $row['text'];
echo "<p>".substr($headline, 0, 110)."... <a href=\"http://www.mysite.com/news/\">Read more</a></p>\n";

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.