PHP 搜索关键字前后X个单词
程序员文章站
2022-05-28 20:26:15
...
//单词不能被拆分//内容里出现多个相同的, 只搜最前一个//省略部分用"..."表示//可以模糊查询//关键字可以是多个单词
麻烦大家帮我看下代码有没有问题(漏掉某种情况没考虑, 代码可以怎么优化下,以及其它问题)
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 = $len) { for ($i = ($start_pos - $max / 2); $i
回复讨论(解决方案)