开发者

Searching Keywords into a Text with a hashtable

I would like to search for keywords in a text, I have around 6000 keywords and I need to know what's the best way to do i开发者_开发百科t in PHP.

What's the best way to implement a hashtable in php?


The question is a bit vague, so I chose a simple scenario/solution ;-)

$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);

prints

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

Which means: the keyword PHP was found 157 times, call 7 times and supercalifragilisticzero times.

Feel free to elaborate on what you're trying and what you need....


A regex would be better because then you could test word boundries. Plus, it's probably quicker.

That being said, here's something.

$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>";


How about a simple array with associative keys? PHP’s array is already implemented with a hash table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜