kaiman Posted January 22, 2010 Share Posted January 22, 2010 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"; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/189449-help-displaying-first-10-words-in-database-field/ Share on other sites More sharing options...
mapleleaf Posted January 22, 2010 Share Posted January 22, 2010 substr will take the first ten characters not words. What does the text look like? Formatted?? Quote Link to comment https://forums.phpfreaks.com/topic/189449-help-displaying-first-10-words-in-database-field/#findComment-1000040 Share on other sites More sharing options...
kaiman Posted January 22, 2010 Author Share Posted January 22, 2010 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"; Quote Link to comment https://forums.phpfreaks.com/topic/189449-help-displaying-first-10-words-in-database-field/#findComment-1000145 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.