[thelist] PHP show first 10 words of MySQL field

Simon Willison cs1spw at bath.ac.uk
Wed Aug 27 21:38:42 CDT 2003


Austin Harris wrote:
> Sorry for the poor title but I am not sure how to describe what I want to do
> concisely...
> 
> I have a text field in a db and want to show on one page just the first 20
> words, (more or less) of that field before putting a "view more" link.
> 
> Being relatively new to PHP I am not sure what sort of function I need to
> use, searching is tricky without being able to state the problem concisely!
> 
> I am guessing I want to count the words, (or characters) and set a cut off
> limit.

The easiest way to do that is like this:

$length = 6; // The number of words you want

$text = 'This text should have come from the MySQL database.';
$words = explode(' ', $text); // Creates an array of words
$words = array_slice($words, 0, $length);
$text = implode(' ', $words);

print $text; // This will contain only the first 6 words

Hope that helps,

Simon Willison
http://simon.incutio.com/




More information about the thelist mailing list