我正在为我的网站编写一个搜索引擎,需要提取带有给定关键字和搜索结果列表中的几个单词的文本块。我的结尾是这样的:
/**
* This function return part of the original text with
* the searched term and few words around the searched term
* @param string $text Original text
* @param string $word Searched term
* @param int $maxChunks Number of chunks returned
* @param int $wordsAround Number of words before and after searched term
*/
public static function searchTerm($text, $word=null, $maxChunks=3, $wordsAround=3) {
$word = trim($word);
if(empty($word)) {
return NULL;
}
$words = explode(' ', $word); // extract single words from searched phrase
$text = strip_tags($text); // clean up the text
$whack = array(); // chunk buffer
$cycle = 0; // successful matches counter
foreach($words as $word) {
$match = array();
// there are named parameters 'pre', 'term' and 'pos'
if(preg_match("/(?P\w+){0,$wordsAround} (?P$word) (?P\w+){0,$wordsAround}/", $text, $match)) {
$cycle++;
$whack[] = $match['pre'] . ' ' . $word . ' ' . $match['pos'];
if($cycle == $maxChunks) break;
}
}
return implode(' | ', $whack);
}这个函数不能工作,但是您可以看到基本的想法。欢迎您提出任何改进正则表达式的建议!
发布于 2010-10-08 12:19:53
如果不使用RegEx对输入进行净化,永远不要将用户内容注入到preg_quote模式中:
http://us3.php.net/manual/en/function.preg-quote.php
发布于 2010-10-08 12:54:18
为什么谷歌在这里没有最好的搜索引擎,我会看看他们的用具
https://stackoverflow.com/questions/3890268
复制相似问题