如何从PHP中存储在我的数据库中的文本中获取前n个单词?

如何从PHP中存储在我的数据库中的文本中获取前n个单词?

问题描述:

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?

我需要知道如何从PHP中存储在我的数据库中的文本中获取前n个单词? p>

例如,如果我的DB中有一些文本像这样: p>

“word1 word2 word3 word4 text one test four four” p> \ n

如何从本文中获得前4或5个单词? p> div>

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

Use the MySQL SUBSTRING INDEX function.

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

Because a regex expression is always nice to have:

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