簡體   English   中英

從字符串中獲取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 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));
}

這是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反向循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM