...

View Full Version : Showing only the first part of an article



Alex!
11-06-2006, 04:47 PM
Hi, I want to get an article(just some text) from a mysql database but only show the first 10 words or so. How would I go about doing this?

thanks
Alex:thumbsup:

littlejones
11-06-2006, 06:10 PM
In future I would suggest you have a summary and then a main content field in the database, then you wouldn't need to chop things up as you could just display the summary. Not that I know what you want to do though :D

Anyway, assuming you know how to pull the field from the database (if you don't then just post again) this is what you could do...




<?php

echo substr($article, 0, 30);

?>




That would show the first 30 characters (which would include spaces). I'm not sure the best way to go about actual words, probably to use the 'explode' function, but if you're not too bothered about the number of words and are more concerned with having roughly the same amount of text then that should do you! :thumbsup:

littlejones
11-06-2006, 06:25 PM
I can see where my first method would cause problems. If you just set it to a fixed length of characters then you may only return part of the last word shown.

In which case I propose you use the explode function.



<?php

$word = explode(" ", $article);

echo $word[0]." ".$word[1]." ".$word[2]." ".$word[3]." ".$word[4]." ".$word[5];

?>



You get the idea? That should display the first 6 words of the article, and it recognises separate words when it comes across a space " " as outlined in the explode statement.

Hope that has been of some help.

littlejones
11-06-2006, 06:35 PM
One more technique which does the same as above but will save you some time...



<?php


$word = explode(" ", $article);

for($i = 0; $i < strlen($article) ; $i++)
{
echo $word[$i]." ";

}
?>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum