计算单词列表的出现次数->然后更新WordPress表中的值


Count occurrences of a list of words -> Then update values in a WordPress table

我正在寻找文本中的多个单词。我从wordpress表(LIST)中获得单词,其中我有两列(WORD和OCCURRENCES):

$result = $wpdb->get_col( "SELECT WORD FROM LIST");
$data = implode('|', $result);
$val = "'/'b($data)'b/i'"; 

然后我用

if(preg_match($val,$text)) { UPDATE OCCURRENCES } 

用于搜索,其中

$val = "'/'b(word1|word2|word3!word4|word5|word6|...)'b/i'"; 

现在的问题是:我如何计数以及如何获得每个单词的出现次数,以便将该值插入到"LIST"表中?这可能吗?

感谢

编辑如果可能的话,我会更好地解释我想要达到的目标。这是我的WordPress表(只是一个例子):

|  ID   |   WORD   |  OCCURRENCES  |
————————————————————————————————————
|   1   |   word1  |       23      | 
|   2   |   word2  |       17      | 
|   3   |   word3  |        9      | 
|   4   |   word4  |        5      | 
|   5   |   word4  |       12      | 

这张表里有一百多个单词。如果找到匹配项,代码应该更新"occurrences value"

您可以使用preg_match_allarray_count_values
试试这样-

$val = "/'bword1|word2|word3'b/i";
//Example text
$text = "word1 word2 word3 word3 word2";
//This matches all occurences
if(preg_match_all($val,$text,$matches) > 0){
    //This counts the frequencies of each occurence
    $res = array_count_values($matches[0]);
    print_r($res);
}
/*OUTPUT
[
     "word1" => 1
     "word2" => 2
     "word3" => 2
]
*/

这是一个可能的解决方案,基于捕获到组1中的单词,然后用array_count_values计算其中的每个关键字:

$text = "word1 word4 word4 word6 word6 word6";
$val = '/'b(word1|word2|word3|word4|word5|word6)'b/i'; 
$arr = array();
if(preg_match_all($val,$text, $matches) > 0) {
    $arr = array_count_values($matches[1]);
    if ($arr["word1"] != NULL) { echo $arr["word1"] . PHP_EOL; };
    if ($arr["word2"] != NULL) { echo $arr["word2"] . PHP_EOL; };
    if ($arr["word3"] != NULL) { echo $arr["word3"] . PHP_EOL; };
    if ($arr["word4"] != NULL) { echo $arr["word4"] . PHP_EOL; };
    if ($arr["word5"] != NULL) { echo $arr["word5"] . PHP_EOL; };
    if ($arr["word6"] != NULL) { echo $arr["word6"] . PHP_EOL; };
} 

参见IDEONE demo

注意如果您不将单词放入组中(我决定使用捕获组),则必须重复单词边界,并且$matches[0]将保存值:

/'bword1'b|'bword2'b|'bword3'b/i