【问题标题】:Count occurrences of a list of words -> Then update values in a WordPress table计算单词列表的出现次数 -> 然后更新 WordPress 表中的值
【发布时间】:2015-10-05 01:30:07
【问题描述】:

我正在寻找文本中的多个单词。我从一个 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      | 

表中有一百多个字。如果我找到匹配项,代码应该更新“出现值”

【问题讨论】:

  • 我认为$val 应该看起来像$val = '/\b(word1|word2|word3|word4|word5|word6|...)\b/i';。解决方案可能是similar to this one。是吗?
  • 非常感谢。我更清楚地更新了问题

标签: php regex wordpress count


【解决方案1】:

您可以为此使用preg_match_all 和array_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
]
*/

【讨论】:

  • 谢谢,解决之路是对的。我更清楚地更新了问题
【解决方案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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
  • 2013-12-25
  • 2021-10-15
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多