我正在打印包含来自给定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