tags:

views:

60

answers:

3

Hi

I need to know how to get the first n words from text stored in my DB in PHP?

for example if there is some text in my DB like this one :

"word1 word2 word3 word4 text one test four five"

How I can get the first 4 or five words from this text?

Thnks in Advance.

+1  A: 

You can use the explode function to split the string by space and get each word:

$words = 'word1 word2 word3 word4 text one test four five';
$words_array = explode(' ', $words);

And then you can use the array_chunk function to get number of words:

print_r(array_chunk($words_array, 4, true));
Sarfraz
+4  A: 

Use the MySQL SUBSTRING INDEX function.

-- Will select everything up until the fifth space.
SELECT SUBSTRING_INDEX(YourTextField, ' ', 5); 
Konerak
A: 

Because a regex expression is always nice to have:

if (preg_match('/([^\\s]*(?>\\s+|$)){0,4}/', $string, $matches)) {
    //result in $matches[0]
}
Artefacto