【发布时间】:2009-10-19 18:28:17
【问题描述】:
我想在文本中搜索关键字,我有大约 6000 个关键字,我需要知道在 PHP 中最好的方法是什么。
在 php 中实现哈希表的最佳方法是什么?
【问题讨论】:
我想在文本中搜索关键字,我有大约 6000 个关键字,我需要知道在 PHP 中最好的方法是什么。
在 php 中实现哈希表的最佳方法是什么?
【问题讨论】:
这个问题有点模糊,所以我选择了一个简单的场景/解决方案;-)
$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 次。
请随意详细说明您正在尝试什么以及您需要什么......
【讨论】:
正则表达式会更好,因为这样您就可以测试单词边界。另外,它可能更快。
话虽如此,这里有一些东西。
$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>";
【讨论】:
带有关联键的简单数组怎么样? PHP 的数组已经用哈希表实现了。
【讨论】: