Home >Backend Development >PHP Tutorial >PHP 搜索关键字前后X个单词
//单词不能被拆分//内容里出现多个相同的, 只搜最前一个//省略部分用"..."表示//可以模糊查询//关键字可以是多个单词
function getSPContent($content, $keyword){ $keyword = trim($keyword); $content = trim(strip_tags($content)); $keyword2 = explode(" ", $keyword); $content2 = explode(" ", $content); $start_pos = "x"; if(count($keyword2) > 1){ foreach ($content2 as $k => $v) { preg_match("/{$keyword2[0]}/", $v, $matches); if (!empty($matches)) { foreach($keyword2 as $x=>$y){ preg_match("/{$keyword2[$x]}/", $content2[$k+$x], $matches); if (!empty($matches) && $x == count($keyword2)-1) { $start_pos = $k; break; }elseif(!empty($matches)){ continue; }else{ break; } } } if($start_pos != "x"){ break; } } }else{ foreach ($content2 as $k => $v) { preg_match("/{$keyword}/", $v, $matches); if (!empty($matches)) { $start_pos = $k; break; } } } $max = 50; $len = count($content2) - 1; $content3 = ""; if ($len < $max) { return $content; } else { if ($start_pos == "x") { for ($i = 0; $i < $max; $i++) { $content3 = $content3 . " " . $content2[$i]; } return ltrim($content3) . "..."; } elseif ($start_pos <= $max / 2) { for ($i = 0; $i < $start_pos + $max / 2; $i++) { $content3 = $content3 . " " . $content2[$i]; } return ltrim($content3) . "..."; } elseif ($start_pos + $max / 2 >= $len) { for ($i = ($start_pos - $max / 2); $i <= $len; $i++) { $content3 = $content3 . " " . $content2[$i]; } return "..." . ltrim($content3); } else { for ($i = $start_pos - $max / 2; $i < $start_pos + $max / 2; $i++) { $content3 = $content3 . " " . $content2[$i]; } return "..." . ltrim($content3) . "..."; } }}