簡體   English   中英

PHP如何提取給定字符串的一部分?

[英]PHP How to extract part of given string?

我正在為我的網站編寫一個搜索引擎,並且需要使用給定的關鍵字和少量單詞來提取文本塊以作為搜索結果列表。 我以這樣的結尾:


/**
 * This function return part of the original text with
 * the searched term and few words around the searched term
 * @param string $text Original text
 * @param string $word Searched term
 * @param int $maxChunks Number of chunks returned
 * @param int $wordsAround Number of words before and after searched term
 */
public static function searchTerm($text, $word=null, $maxChunks=3, $wordsAround=3) {
        $word = trim($word);
        if(empty($word)) {
            return NULL;
        }
        $words = explode(' ', $word); // extract single words from searched phrase
        $text  = strip_tags($text);  // clean up the text
        $whack = array(); // chunk buffer
        $cycle = 0; // successful matches counter
        foreach($words as $word) {
            $match = array();
            // there are named parameters 'pre', 'term' and 'pos'
            if(preg_match("/(?P\w+){0,$wordsAround} (?P$word) (?P\w+){0,$wordsAround}/", $text, $match)) {
                $cycle++;
                $whack[] = $match['pre'] . ' ' . $word . ' ' . $match['pos'];
                if($cycle == $maxChunks) break;
            }
        }
        return implode(' | ', $whack);
    }
此功能不起作用,但是您可以看到基本思想。 歡迎提出任何改進正則表達式的建議!

永遠, 永遠注入用戶內容插入到正則表達式的圖案而無需使用preg_quote到凈化輸入:

http://us3.php.net/manual/en/function.preg-quote.php

為什么在這里重新發明輪子谷歌沒有最好的搜索引擎,我會看看他們的設備

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM