PHP 获取字符串前 5 个单词的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2915661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:07:03  来源:igfitidea点击:

PHP What is the best way to get the first 5 words of a string?

phpstring

提问by Mithun Sreedharan

What is the best way to get the first 5 words of a string? How can I split the string into two in such a way that first substring has the first 5 words of the original string and the second substring constitutes the rest of the original string

获取字符串前 5 个单词的最佳方法是什么?如何将字符串分成两部分,使第一个子字符串具有原始字符串的前 5 个单词,第二个子字符串构成原始字符串的其余部分

回答by Amber

$pieces = explode(" ", $inputstring);
$first_part = implode(" ", array_splice($pieces, 0, 5));
$other_part = implode(" ", array_splice($pieces, 5));

explodebreaks the original string into an array of words, array_splicelets you get certain ranges of those words, and then implodecombines the ranges back together into single strings.

explode将原始字符串分解为单词数组,array_splice让您获得这些单词的特定范围,然后implode将这些范围重新组合成单​​个字符串。

回答by salathe

The following depends strongly on what you define as a wordbut it's a nod in another direction, away from plain explode-ing.

以下在很大程度上取决于您对单词的定义,但它是对另一个方向的点头,远离简单的explode-ing。

$phrase = "All the ancient classic fairy tales have always been scary and dark.";
echo implode(' ', array_slice(str_word_count($phrase, 2), 0, 5));

Gives

All the ancient classic fairy

所有的古代经典仙女



Another alternative, since everyone loves regex, would be something like:

另一种选择,因为每个人都喜欢正则表达式,就像:

preg_match('/^(?>\S+\s*){1,5}/', $phrase, $match);
echo rtrim($match[0]);

回答by Kenaniah

<?php
$words = explode(" ", $string);
$first = join(" ", array_slice($words, 0, 5));
$rest = join(" ", array_slice($words, 5));

回答by Shiv Singh

implode(' ', array_slice(explode(' ', $contents), 0, 5));

Note:here at the last you can see 0, 10 it will print from start word to 10th word, so you can fix as you want to start from word to total number of word.

注意:在最后你可以看到 0, 10 它将从起始词打印到第 10 个词,因此您可以根据需要从单词开始到单词总数进行修复。