substr_count()计算php中的整词
我是php的新手,所以我在做一个单词计数器程序。我试着数一数一个网站上有多少特定单词的实例。 所以,我使用Substr_count来计算单词,但问题是它将像sunlight这样的单词视为包含像sun这样的单词 这是我的密码substr_count()计算php中的整词,php,search,word,Php,Search,Word,我是php的新手,所以我在做一个单词计数器程序。我试着数一数一个网站上有多少特定单词的实例。 所以,我使用Substr_count来计算单词,但问题是它将像sunlight这样的单词视为包含像sun这样的单词 这是我的密码 /*When the user types the word*/ $search = $_POST["texto"]; /*The website*/ $page = $_POST["Web"]; $web = file_get_contents($page)
/*When the user types the word*/
$search = $_POST["texto"];
/*The website*/
$page = $_POST["Web"];
$web = file_get_contents($page);
/*Count words*/
$result = (substr_count(strip_tags(strtolower($web)), strtolower($search)));
/*Display the information*/
if($result == 0){
echo "the word " .mb_strtoupper($search). " doesn't appear";
}else{
echo "the word " .mb_strtoupper($search). " appears $result times";
}
有办法解决这个问题吗?我尝试了str\u-word\u-count和preg\u-match\u-all,但这会显示较大的数字。我会使用str\u-word\u-count的组合来获取所有单词和数组\u-count\u值,以计算这些单词出现的次数:
# Get an array with lowercase words
$array_with_words = str_word_count(strtolower('string to analyze'), 1);
# Get a count of all unique values
$array_with_words_count = array_count_values($array_with_words);
# Get the count of the word you are looking for
$your_count = $array_with_words_count[ strtolower('your_word') ];
str_word_cound$expression,1函数将为您提供一个与单词相关的数组,然后您可以使用foreach循环一次,并构建一个具有单词频率的数组,如下所示:
$expr = "My test expression. <b>My</b> world.";
$words = str_word_count(strip_tags(strtolower($expr)), 1);
$groupedWords = [];
foreach ($words as $word) {
print_r($word);
$groupedWords[$word] ++;
}
print_r($groupedWords);
要查看一个单词被使用了多少次,请执行以下操作:
var_dump(array_key_exists('specific_word_you_look_for', $groupedWords) ? $groupedWords['specific_word_you_look_for'] : false);
// will output the frequency or false if not found
如果要使用预定义函数,请使用str\u word\u count 例如:
输出:3这将完成以下操作:
/*Count words*/
$result = preg_match_all('/\b'. strtolower($search) .'\b/', strtolower($web));
计算机怎么知道它只能拾取太阳光而不能拾取太阳光?你能把一些样本数据添加到列表中吗question@Wolvysubstr-完全代表次小部分、较小部分和字符串。。。它没有考虑什么词are@Wolvy-应该考虑使用正则表达式。instead@Wolvy,使用正则表达式。检查此主题检查是否计算字数总数,而不是特定字词在字符串中出现的次数。谢谢,您的解决方案有效无问题Wolvy
<?php
echo str_word_count("stack gives answer");
?>
/*Count words*/
$result = preg_match_all('/\b'. strtolower($search) .'\b/', strtolower($web));