簡體   English   中英

取得3個字的字串數

[英]Get 3 words count in string

我試圖只在一個字符串中獲得3個單詞的單詞頻率。 例如:

$ string =“這是一個示例文本。它是作為示例的示例文本。”;

我想要輸出:

“是一個樣本”(2)

“示例文本”(2)

.... 等等

提前致謝。

用空格作為分隔符來展開句子並循環通過。

<?php
$string = "This is a sample text. It is a sample text used as an example.";
$arr = explode(' ',$string);
$i=0;
foreach($arr as $k=>$v)
{
echo $arr[$i]." ".$arr[$i+1]." ".$arr[$i+2]."<br>";
$i++;
}

OUTPUT :

This is a
is a sample
a sample text.
sample text. It
text. It is
It is a
is a sample
a sample text
sample text used
.....
$string = "This is a sample text. It is a sample text used as an example.";
$words = preg_split('/\W/', $string);
$wordsPerRow = 3;


$offset = 0;
while ($offset < count($words)) {
    print implode(' ', array_slice($words, $offset, $wordsPerRow)).PHP_EOL;
    $offset += $wordsPerRow;
}

暫無
暫無

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

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