簡體   English   中英

如何突出顯示搜索結果

[英]how to highlight search results

你好,我有一個搜索功能,我會在數據庫中搜索關鍵字。 我想突出顯示關鍵字,並找到了我希望在我的搜索功能中實現的第二個功能。

所以我有這個搜索代碼:

<?php 
function searchText($keywords){
    global $db;
    $returned_results = array();
    $where2 = "";

    $keywords = preg_split('/[\s]+/', $keywords); 
    $total_keywords = count($keywords);

    foreach ($keywords as $key=>$keyword){
        $where2 .= "`column` LIKE '%$keyword%'";

        if ($key != ($total_keywords - 1)){ 
            $where2 .= " OR ";
        }
    }

    $results_text = "SELECT `a`, `b`, LEFT(`c`, 150) as `c` FROM `table` WHERE $where2"; 
    $results_num_text = ($query2 = mysqli_query($db, $results_text)) ? mysqli_num_rows($query2) : 0; 
    if ($results_num_text === 0){
        return false;
    } else {

        while ($row = mysqli_fetch_assoc($query2)){

            $returned_results[] = array(
                'ab' => $row['ab'],
                'cd' => $row['cd'], 
            );
        }

        return $returned_results;
    }
}
?>

並希望在其中實現第二個功能:

<?php
function mark_words ($text, $words, $colors = false)
{

    if (!$colors || !is_array($colors) ) {
        $colors = array('#ff9999', '#ffff99', '#ff99ff', '#99ffff','#99ff99');
    }

    $c = 0;

    foreach ($words as $w) {

        $w = preg_quote(trim($w));

        if($w=='') {
            continue;
        }

        $regexp = "/($w)(?![^<]+>)/i";

        $replacement = '<b style="background-color:'.$colors[$c].'">\\1</b>';

        $text = preg_replace ($regexp,$replacement ,$text);

        $c++;
        if ($c >= count($colors)) {
            $c=0;
        }
    }
    return $text;
}

$example = <<< EOT
some text is here inside
EOT;

$search = array('some','is', 'inside');

echo mark_words($example, $search);
?> 

所以我有這個代碼不起作用:

<?php 
function searchText($keywords, $colors = false){
    global $db;

     if (!$colors || !is_array($colors) ) {
        $colors = array('#ff9999', '#ffff99', '#ff99ff', '#99ffff','#99ff99');
    }

    $c = 0;

    $returned_results = array();
    $where2 = "";

    $keywords = preg_split('/[\s]+/', $keywords); 
    $total_keywords = count($keywords);

    foreach ($keywords as $key=>$keyword){

    $regexp = "/($w)(?![^<]+>)/i";
        $replacement = '<b style="background-color:'.$colors[$c].'">\\1</b>';

        $text = preg_replace($regexp,$replacement ,$keywords);
        $c++;

        if ($c >= count($colors)) {
            $c=0;
        }

        $where2 .= "`b` LIKE '%$keyword%'";

        if ($key != ($total_keywords - 1)){ 
            $where2 .= " OR ";
        }
    }

    $results_text = "SELECT `a`, LEFT(`b`, 150) as `b`, `c` FROM `table` WHERE $where2";
    $results_num_text = ($query2 = mysqli_query($db, $results_text)) ? mysqli_num_rows($query2) : 0; 
    if ($results_num_text === 0){
        return false;
    } else {

        while ($row = mysqli_fetch_assoc($query2)){

            $returned_results[] = array(
                'ab' => $row['a'],
                'cd' => $row['b'],
            );
        }

        return $returned_results;
        $highlight = array($keywords);
        echo mark_words($highlight);
    }
}
?>

當我尋找它時如何做到這一點我找到了兩種可能性。 第一個是一個函數,第二個是直接從select查詢中突出顯示它:

SELECT
        REPLACE(`col`, 'foobar', '<span class="highlight">foobar</span>') AS `formated_foobar`
  FROM
        …
  WHERE
        `col` LIKE "%foobar%"

所以我的問題是我如何在搜索功能中實現第二個功能,或者使用第二個方法會更好嗎?

如果有人可以幫助我,我真的很感激。 非常感謝。

你不應該為自己太難。 所有你需要的是用應用了所需樣式的span中包含的單詞替換每個單詞的出現。 這應該適合你:

function highlight_word( $content, $word, $color ) {
    $replace = '<span style="background-color: ' . $color . ';">' . $word . '</span>'; // create replacement
    $content = str_replace( $word, $replace, $content ); // replace content

    return $content; // return highlighted data
}

function highlight_words( $content, $words, $colors ) {
    $color_index = 0; // index of color (assuming it's an array)

    // loop through words
    foreach( $words as $word ) {
        $content = highlight_word( $content, $word, $colors[$color_index] ); // highlight word
        $color_index = ( $color_index + 1 ) % count( $colors ); // get next color index
    }

    return $content; // return highlighted data
}



// words to find
$words = array(
    'normal',
    'text'
);

// colors to use
$colors = array(
    '#88ccff',
    '#cc88ff'
);

// faking your results_text
$results_text = array(
    array(
        'ab'    => 'AB #1',
        'cd'    => 'Some normal text with normal words isn\'t abnormal at all'
    ), array(
        'ab'    => 'AB #2',
        'cd'    => 'This is another text containing very normal content'
    )
);

// loop through results (assuming $output1 is true)
foreach( $results_text as $result ) {
    $result['cd'] = highlight_words( $result['cd'], $words, $colors );

    echo '<fieldset><p>ab: ' . $result['ab'] . '<br />cd: ' . $result['cd'] . '</p></fieldset>';
}

使用正則表達式替換內容也可以,但使用str_replace()會更快一些。

函數接受以下參數:

highlight_word( string, string, string );

highlight_words( string, array, array );

以上示例導致:

在此輸入圖像描述

通過使用str_ireplace而不是str_replace,該函數將不區分大小寫

我不會使用SQL方法。 隨着時間的推移,你有越來越多的突出規則,這將變得無法管理。 處理需要以不同於foobar方式突出顯示foo的情況也比較棘手,但其中一個包含另一個。

將數據處理與格式分開。

暫無
暫無

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

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