从字符串中获取X个第一个/最后一个单词


Get X first/last WORDS from string

好吧,这就是我需要的。。。

示例输入:

$str = "Well, I guess I know what this # is : it is a & ball";

示例输出:

  • firstWords($str,5)应返回Array("Well","I","guess","I","know")
  • lastWords($str,5)应返回Array("is","it","is","a","ball")

我已经尝试过使用自定义正则表达式和str_word_count,但我仍然觉得我遗漏了一些东西。

有什么想法吗?

您只需要

$str = "Well, I guess I know what this # is : it is a & ball";
$words = str_word_count($str, 1);
$firstWords = array_slice($words, 0,5);
$lastWords = array_slice($words, -5,5);
print_r($firstWords);
print_r($lastWords);

输出

Array
(
    [0] => Well
    [1] => I
    [2] => guess
    [3] => I
    [4] => know
)
Array
(
    [0] => is
    [1] => it
    [2] => is
    [3] => a
    [4] => ball
)

这是第一个单词:

function firstWords($word, $amount)
    {
        $words = explode(" ", $word);
        $returnWords = array();
        for($i = 0; $i < count($words); $i++)
        {
            $returnWords[] = preg_replace("/(?![.=$'€%-])'p{P}/u", "", $words[$i]);
        }
        return $returnWords;
    }

for lastWords reverse for loop。

function cleanString($sentence){
    $sentence = preg_replace("/[^a-zA-Z0-9 ]/","",$sentence);
    while(substr_count($sentence, "  ")){
        str_replace("  "," ",$sentence);
    }
    return $sentence;
}
function firstWord($x, $sentence){
    $sentence = cleanString($sentence);
    return implode(' ', array_slice(explode(' ', $sentence), 0, $x));
}
function lastWord($x, $sentence){
    $sentence = cleanString($sentence);
    return implode(' ', array_slice(explode(' ', $sentence), -1*$x));
}