I need to know how to get the first n words from text stor开发者_如何转开发ed 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?
Use the MySQL SUBSTRING INDEX function.
-- Will select everything up until the fifth space.
SELECT SUBSTRING_INDEX(YourTextField, ' ', 5);
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));
Because a regex expression is always nice to have:
if (preg_match('/([^\\s]*(?>\\s+|$)){0,4}/', $string, $matches)) {
//result in $matches[0]
}
精彩评论