Home >Backend Development >PHP Tutorial >PHP 搜索关键字前后X个单词

PHP 搜索关键字前后X个单词

WBOY
WBOYOriginal
2016-06-20 09:37:04942browse

//单词不能被拆分//内容里出现多个相同的, 只搜最前一个//省略部分用"..."表示//可以模糊查询//关键字可以是多个单词


麻烦大家帮我看下代码有没有问题(漏掉某种情况没考虑, 代码可以怎么优化下,以及其它问题)

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) . "...";        }    }}


回复讨论(解决方案)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn