【问题标题】:Searching Keywords into a Text with a hashtable使用哈希表将关键字搜索到文本中
【发布时间】:2009-10-19 18:28:17
【问题描述】:

我想在文本中搜索关键字,我有大约 6000 个关键字,我需要知道在 PHP 中最好的方法是什么。

在 php 中实现哈希表的最佳方法是什么?

【问题讨论】:

    标签: php hashtable search


    【解决方案1】:

    这个问题有点模糊,所以我选择了一个简单的场景/解决方案;-)

    $keywords = array('PHP', 'introduction', 'call', 'supercalifragilistic');
    $text = file_get_contents('http://www.php.net/archive/2009.php'); // including all the html markup, only an example
    $words = array_count_values(str_word_count($text, 2));
    $result = array_intersect_key($words, array_flip($keywords));
    var_dump($result);
    

    打印

    array(2) {
      ["PHP"]=>
      int(157)
      ["call"]=>
      int(7)
    }
    

    这意味着:关键字 PHP 被找到 157 次,call 7 次和 supercalifragilistic0 次。

    请随意详细说明您正在尝试什么以及您需要什么......

    【讨论】:

      【解决方案2】:

      正则表达式会更好,因为这样您就可以测试单词边界。另外,它可能更快。

      话虽如此,这里有一些东西。

      $needles = array('cat','dog','fox','cow');
      $haystack = 'I like cats and dogs, but my favorie animal is the cow';
      
      $hash = array();
      foreach($needles as $needle){
          if (strstr($haystack,$needle)){
              $hash[$needle] = 1;
          }
      }
      
      echo "<pre>";
      print_r(array_keys($hash));
      echo "</pre>";
      

      【讨论】:

      • 嗯,好吧,但是,你如何在一个正则表达式中测试 6000 个单词? (他们有不同的模式)
      • 正则表达式将取代 strstr 函数。 strstr 函数只是查看目标字符串是否在字符串中。
      【解决方案3】:

      带有关联键的简单数组怎么样? PHP 的数组已经用哈希表实现了。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-07
      • 2023-03-29
      • 2014-01-04
      • 2014-07-08
      • 2015-06-07
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      相关资源
      最近更新 更多