我正在尝试使用substr_count从一个文本块中提取某些关键字组,并计算每个组中单词出现的次数。
我创建了一个名为$ keywords的数组,其中包含另一组包含我正在寻找的实际关键字的数组。
这是我目前的代码:
$textDump = "random bunch of text";
$keyWordsSports = array("nba", "raptor", "ufc", "basektball", "gym", "mma", "realgm", "running");
$keyWordsTech = array("apple", "rim", "blackberry", "facebook", "twitter", "google" );
$keywords = array($keyWordsSports, $keyWordsTech);
foreach ($keywords as $item){
foreach ($item as $newItem){
$number += substr_count(strtolower($textDump), strtolower($newItem));
echo $number;
};
};
我的问题是,它计算所有数组中的所有关键字并将所有内容添加到一起,我想要的只是每组关键字的总数。关于我应该做什么的任何想法?
答案 0 :(得分:3)
$keywords = array("sports"=>$keyWordsSports, "tech"=>$keyWordsTech);
$count=array("sports"=>0,"tech"=>0);
foreach ($keywords as $key=>$item){
foreach ($item as $newItem){
$count[$key] += substr_count(strtolower($textDump), strtolower($newItem));
}
}
print_r($count);
修改:Live example
答案 1 :(得分:1)
试试这个:
$textDump = "raptor bunch raptor basektball";
$keyWordsSports = array("nba", "raptor", "ufc", "basektball", "gym", "mma", "realgm", "running");
$keyWordsTech = array("apple", "rim", "blackberry", "facebook", "twitter", "google" );
$keywords = array($keyWordsSports, $keyWordsTech);
$matches=array();
foreach ($keywords as $item){
foreach ($item as $newItem){
$number = substr_count(strtolower($textDump), strtolower($newItem));
if($number>0)
{
$matches[strtolower($newItem)]=$number;
}
};
};
print_r($matches);
答案 2 :(得分:0)
你只需要echo
内$number
以外的foreach
$textDump = "random bunch of text";
$keyWordsSports = array("nba", "raptor", "ufc", "basektball", "gym", "mma", "realgm", "running");
$keyWordsTech = array("apple", "rim", "blackberry", "facebook", "twitter", "google" );
$keywords = array($keyWordsSports, $keyWordsTech);
foreach ($keywords as $item) {
foreach ($item as $newItem) {
$number += substr_count(strtolower($textDump), strtolower($newItem));
}
echo $number;
}
像这样,
{{1}}