【发布时间】:2010-06-10 10:36:39
【问题描述】:
我需要知道如何从 PHP 中存储在我的数据库中的文本中获取前 n 个单词?
例如,如果我的数据库中有这样的文本:
"word1 word2 word3 word4 text 一测四五"
我怎样才能得到这篇文章的前 4 或 5 个单词?
【问题讨论】:
我需要知道如何从 PHP 中存储在我的数据库中的文本中获取前 n 个单词?
例如,如果我的数据库中有这样的文本:
"word1 word2 word3 word4 text 一测四五"
我怎样才能得到这篇文章的前 4 或 5 个单词?
【问题讨论】:
使用 MySQL SUBSTRING INDEX 函数。
-- Will select everything up until the fifth space.
SELECT SUBSTRING_INDEX(YourTextField, ' ', 5);
【讨论】:
您可以使用explode函数将字符串按空格分割并获取每个单词:
$words = 'word1 word2 word3 word4 text one test four five';
$words_array = explode(' ', $words);
然后你可以使用 array_chunk 函数来获取字数:
print_r(array_chunk($words_array, 4, true));
【讨论】:
因为拥有一个正则表达式总是很不错的:
if (preg_match('/([^\\s]*(?>\\s+|$)){0,4}/', $string, $matches)) {
//result in $matches[0]
}
【讨论】: