PHP 搜尋索引鍵前後X個單詞

來源:互聯網
上載者:User
//單詞不能被拆分//內容裡出現多個相同的, 只搜最前一個//省略部分用"..."表示//可以模糊查詢//關鍵字可以是多個單詞


麻煩大家幫我看下代碼有沒有問題(漏掉某種情況沒考慮, 代碼可以怎麼最佳化下,以及其它問題)

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


回複討論(解決方案)

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.