标题确实不好,但是我不确定如何描述我要实现的目标...基本上,我的网站收到了很多用户输入,我正在寻找通过句子中的关键字创建得分的方法由用户制作。
例如;
评论-This video was trash I can't believe you would upload something like this
video
= 5 trash
= 8 was
= 6
由于包含关键字的短语,返回的总和为19
到目前为止,我已经尝试使用很多strpos
if语句,但是如果重复单词,它们不会叠加,所以我决定使用substr_count
并乘以数字,但这对于其他单词之内的较小单词是个问题……我只是好奇是否有更好的方法来做到这一点?这是一种使每个单词等于分数的单词列表的方法...在此先感谢,如果这没有什么意义,请您多谢,但我一直难以描述。
答案 0 :(得分:2)
我建议进行爆炸以分隔单词,然后进行循环,沿这些方向进行操作:
$string = 'This video was trash I can\'t believe you would upload something like this';
$key_words = array(
'video' => 5,
'thrash' => 8,
'was' => 6
);
$score = 0;
$exploded_string = explode(' ', $string);
foreach($exploded_string as $substr){
if($key_words[$substr]){
$score += $key_words[$substr];
}
}
答案 1 :(得分:0)
我建议以下内容:
未经测试:
$values = array("video" => 5, "trash" => 8);
$str = "This video was trash";
$words = explode(" ", $str);
$occurrences = array_count_values($words);
$total = 0;
foreach($values as $word => $value) {
if(isset($occurrences [$word])) {
$total += $value * $occurrences [$word];
}
}
答案 2 :(得分:0)
如果您打算直接从评论中获得分数,那么我建议您使用preg_match()
。
$comment_string = 'some_comment_string video = 4 was : 6 thrash = 9';
$ratings = [
'video' => 0,
'thrash' => 0,
'was' => 0,
];
$sum = 0;
foreach($ratings as $search=>$value){
preg_match('#' . $search . '\s*[:|=]\s*([0-9]+)#', $comment_string, $match);
if(isset($match[1])){
$ratings[$search] = $match[1];
$sum += $match[1];
}
}
// do anything with $ratings array OR
echo $sum;
使用正则表达式,您可以更好地控制字符串。就像接受=
或:
作为乐谱名称和实际值之间的分隔符一样。 \s
也允许忽略空格。
请为用户评估的每个属性分别考虑输入。