我正在打印包含來自給定url的HTML內容的字符串。我想要做的是找出字符串中有多少個單詞以及它們出現的次數。計算字符串中的字數量php
例如:
今天| 1
如何| 1
你好| 1
代碼:
$string = "Hello how are you today"
我正在打印包含來自給定url的HTML內容的字符串。我想要做的是找出字符串中有多少個單詞以及它們出現的次數。計算字符串中的字數量php
例如:
今天| 1
如何| 1
你好| 1
代碼:
$string = "Hello how are you today"
把你的$ cResult作爲輸入:
$word_counts = [];
// remove scripts and styles completely, then strip tags
$cResult = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $cResult);
$cResult = preg_replace('#<style(.*?)>(.*?)</style>#is', '', $cResult);
$cResult = strip_tags($cResult);
// strip all characters that are not letters:
$word_array_raw = explode(' ',preg_replace('/[^A-Za-z ]/', ' ', $cResult));
// loop through array:
foreach ($word_array_raw as $word) {
$word = trim($word);
if($word) {
isset($word_counts[$word]) ? $word_counts[$word]++ : $word_counts[$word] = 1;
}
}
// Array with all stats sorted in descending order:
arsort($word_counts);
// Output format you wanted:
foreach ($word_counts as $word=>$count) {
echo "$word | $count<br>";
}
希望它可以幫助
有沒有辦法從結果中刪除html標籤名稱? – user7588392
新增了strip_tags – paulz
我試過了。這只是刪除括號。我仍然留下這個詞。例如,getElementById。 – user7588392
事情是這樣的:
$s = "lorem ipsum dolor sit amet, consectetur adipiscing elit, sit sed do lorem eiusmod tempor";
$w = preg_split('=[^\w]=', $s, NULL, PREG_SPLIT_NO_EMPTY);
$words = [];
foreach ($w as $word) {
if (!isset($words[$word])) $words[$word] = 0;
$words[$word]++;
}
print_r($words);
輸出:
Array
(
[lorem] => 2
[ipsum] => 1
[dolor] => 1
[sit] => 2
[amet] => 1
[consectetur] => 1
[adipiscing] => 1
[elit] => 1
[sed] => 1
[do] => 1
[eiusmod] => 1
[tempor] => 1
)
這就是你想要的?
我不知道你的代碼中有你的問題做的,但你可以嘗試['str_split()'] (http://php.net/manual/en/function.str-split.php)將它拆分爲空格,然後遍歷數組,然後在另一個數組中使用單詞作爲鍵,每次遞增。如果你想分割任何字邊界,使用['preg_split()'](http://php.net/manual/en/function.str-split.php)並在'\ b'上分割。就在我頭頂。 – alanlittle