1

好的,这就是我需要的...

示例输入:

$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,但我仍然觉得好像我错过了一些东西。

有任何想法吗?

4

3 回答 3

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
)
于 2013-07-17T12:33:28.807 回答
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));
}
于 2013-07-17T12:33:10.503 回答
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 反向 for 循环。

于 2013-07-17T12:35:30.793 回答