Saleh
Saleh

Reputation: 2719

How to get the first n words from text stored in my DB in PHP?

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?

Upvotes: 1

Views: 2005

Answers (3)

Artefacto
Artefacto

Reputation: 97845

Because a regex expression is always nice to have:

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

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382881

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));

Upvotes: 1

Konerak
Konerak

Reputation: 39773

Use the MySQL SUBSTRING INDEX function.

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

Upvotes: 7

Related Questions