简体   繁体   English

如何突出显示搜索结果

[英]how to highlight search results

hello i have a search function in that i will search a db for keywords. 你好,我有一个搜索功能,我会在数据库中搜索关键字。 i would like to highlight the keywords and found a second function that i would like to implement into my search function. 我想突出显示关键字,并找到了我希望在我的搜索功能中实现的第二个功能。

so i have this code for the search: 所以我有这个搜索代码:

<?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;
    }
}
?>

and would like to implement a second function into it: 并希望在其中实现第二个功能:

<?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);
?> 

so i have this code that doesnt work: 所以我有这个代码不起作用:

<?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);
    }
}
?>

as i looked for it how to do so i found two possibilities. 当我寻找它时如何做到这一点我找到了两种可能性。 the first would be a function the second would be directly to highlight it from the select query: 第一个是一个函数,第二个是直接从select查询中突出显示它:

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

so my question is how can i implement the second function into the search function or would it be better to use the second method? 所以我的问题是我如何在搜索功能中实现第二个功能,或者使用第二个方法会更好吗?

if there is someone who could help me i really would appreciate. 如果有人可以帮助我,我真的很感激。 thanks a lot. 非常感谢。

You shouldn't make it too hard for yourself. 你不应该为自己太难。 All you need it to replace every occurrence of a word with the word wrapped in the span with the required style applied. 所有你需要的是用应用了所需样式的span中包含的单词替换每个单词的出现。 This should work for you: 这应该适合你:

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>';
}

Using Regular Expressions to replace content would do as well, though using str_replace() is a bit faster. 使用正则表达式替换内容也可以,但使用str_replace()会更快一些。

The functions accepts these arguments: 函数接受以下参数:

highlight_word( string, string, string );

highlight_words( string, array, array );

The above example results in: 以上示例导致:

在此输入图像描述

通过使用str_ireplace而不是str_replace,该函数将不区分大小写

I would not use the SQL method. 我不会使用SQL方法。 As time goes on, and you have more and more highlighting rules, that will become unmanageable. 随着时间的推移,你有越来越多的突出规则,这将变得无法管理。 Also trickier to handle the cases where you need to highlight foo differently to foobar , but one contains the other. 处理需要以不同于foobar方式突出显示foo的情况也比较棘手,但其中一个包含另一个。

Separate your data handling from your formatting. 将数据处理与格式分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM