我试图仅在字符串中获得3个单词的单词频率。例如:
$ string =“这是一个示例文本。它是一个示例文本,用作示例。”;
我想要输出:
“是一个样本”(2)
“示例文本”(2)
....等等
提前致谢。
答案 0 :(得分:0)
用空格作为分隔符来爆炸句子并循环。
<?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
.....
答案 1 :(得分:0)
$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;
}