How to generate excerpt with most searched words in PHP?

前端 未结 4 906
栀梦
栀梦 2020-12-20 03:07

Here is an excerpt function:

    function excerpt($text, $phrase, $radius = 100, $ending = \"...\") {
270             if (empty($text) or empty($phrase)) {
2         


        
4条回答
  •  既然无缘
    2020-12-20 03:17

    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; }
    

提交回复
热议问题