如何选择一个句子的前10个单词? [英] How to select first 10 words of a sentence?
本文介绍了如何选择一个句子的前10个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从输出中仅选择前10个字?
How do I, from an output, only select the first 10 words?
推荐答案
implode(' ', array_slice(explode(' ', $sentence), 0, 10));
要增加对其他分词符(如逗号和破折号)的支持,preg_match
提供了一种快速方法,不需要拆分字符串:
To add support for other word breaks like commas and dashes, preg_match
gives a quick way and doesn't require splitting the string:
function get_words($sentence, $count = 10) {
preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
return $matches[0];
}
如Pebbl所述,PHP不能很好地处理UTF-8或Unicode,因此,如果您对此感到担忧,则可以将\w
替换为[^\s,\.;\?\!]
,将\W
替换为[\s,\.;\?\!]
.
As Pebbl mentions, PHP doesn't handle UTF-8 or Unicode all that well, so if that is a concern then you can replace \w
for [^\s,\.;\?\!]
and \W
for [\s,\.;\?\!]
.
这篇关于如何选择一个句子的前10个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文