Kel*_*lly 125
implode(' ', array_slice(explode(' ', $sentence), 0, 10));
Run Code Online (Sandbox Code Playgroud)
要添加对其他单词分隔符(如逗号和短划线)的支持,请preg_match
提供快速方法,并且不需要拆分字符串:
function get_words($sentence, $count = 10) {
preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
return $matches[0];
}
Run Code Online (Sandbox Code Playgroud)
正如Pebbl所提到的,PHP并不能很好地处理UTF-8或Unicode,所以如果这是一个问题,那么你可以替换\w
for [^\s,\.;\?\!]
和\W
for [\s,\.;\?\!]
.
Peb*_*bbl 52
如果在句子结构中存在意外的字符代替空格,或者句子包含多个连接的空格,则简单地拆分空格将无法正常工作.
无论您在单词之间使用何种"空间",以下版本都可以使用,并且可以轻松扩展以处理其他字符...它目前支持任何空格字符加,.; ?!
function get_snippet( $str, $wordCount = 10 ) {
return implode(
'',
array_slice(
preg_split(
'/([\s,\.;\?\!]+)/',
$str,
$wordCount*2+1,
PREG_SPLIT_DELIM_CAPTURE
),
0,
$wordCount*2-1
)
);
}
Run Code Online (Sandbox Code Playgroud)
正则表达式非常适合这个问题,因为您可以轻松地使代码变得灵活或严格.但是你必须要小心.我特别针对上述目标之间的差距 - 而不是单词本身 - 因为很难明确地说明定义单词的内容.
取\w
字边界或其反转\W
.我很少依赖这些,主要是因为 - 取决于您使用的软件(如某些版本的PHP) - 它们并不总是包含UTF-8或Unicode字符.
在正则表达式中,最好始终具体.因此,无论表达式在何处呈现,您的表达式都可以处理以下内容:
echo get_snippet('??? ?? ?? ??????, ??????? ?? ?????', 5);
/// outputs: ??? ?? ?? ??????, ???????
Run Code Online (Sandbox Code Playgroud)
然而,就性能而言,避免分裂可能是值得的.所以,你可以用凯利的更新方法,但切换\w
为[^\s,\.;\?\!]+
与\W
对[\s,\.;\?\!]+
.虽然,我个人喜欢上面使用的分裂表达式的简单性,但它更容易阅读并因此修改.然而,PHP函数的堆栈有点难看:)
http://snipplr.com/view/8480/a-php-function-to-return-the-first-n-words-from-a-string/
function shorten_string($string, $wordsreturned)
{
$retval = $string; // Just in case of a problem
$array = explode(" ", $string);
/* Already short enough, return the whole thing*/
if (count($array)<=$wordsreturned)
{
$retval = $string;
}
/* Need to chop of some words*/
else
{
array_splice($array, $wordsreturned);
$retval = implode(" ", $array)." ...";
}
return $retval;
}
Run Code Online (Sandbox Code Playgroud)