例如,它只返回搜索关键词所在的片段。
并且部分文字被“...”所取代。
是否可以使用 PHP 和 MySQL 实现该目标?
稍微修改了 deceze 的功能以允许多个短语。例如你的短语可以是“testa testb”,如果它没有找到 testa,那么它将转到 testb。
function excerpt($text, $phrase, $radius = 100, $ending = "...") {
$phraseLen = strlen($phrase);
if ($radius < $phraseLen) {
$radius = $phraseLen;
}
$phrases = explode (' ',$phrase);
foreach ($phrases as $phrase) {
$pos = strpos(strtolower($text), strtolower($phrase));
if ($pos > -1) break;
}
$startPos = 0;
if ($pos > $radius) {
$startPos = $pos - $radius;
}
$textLen = strlen($text);
$endPos = $pos + $phraseLen + $radius;
if ($endPos >= $textLen) {
$endPos = $textLen;
}
$excerpt = substr($text, $startPos, $endPos - $startPos);
if ($startPos != 0) {
$excerpt = substr_replace($excerpt, $ending, 0, $phraseLen);
}
if ($endPos != $textLen) {
$excerpt = substr_replace($excerpt, $ending, -$phraseLen);
}
return $excerpt;
}
高亮功能
function highlight($c,$q){
$q=explode(' ',str_replace(array('','\\','+','*','?','[','^',']','$','(',')','{','}','=','!','<','>','|',':','#','-','_'),'',$q));
for($i=0;$i
$c=preg_replace("/($q[$i])(?![^<]*>)/i","\${1}",$c);
return $c;}
Tôi là một lập trình viên xuất sắc, rất giỏi!