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

时间:2013-07-17 12:28:13

标签: php 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,但我仍然觉得我错过了某些东西。

有什么想法吗?

3 个答案:

答案 0 :(得分:6)

你需要的只是

$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
)

答案 1 :(得分:0)

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));
}

答案 2 :(得分:0)

这是firstWord:

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。