如何突出显示搜索结果

时间:2012-04-25 09:57:54

标签: php mysql html function syntax-highlighting

你好,我有一个搜索功能,我会在数据库中搜索关键字。我想突出显示关键字,并找到了我希望在我的搜索功能中实现的第二个功能。

所以我有这个搜索代码:

<?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%"

所以我的问题是我如何在搜索功能中实现第二个功能,或者使用第二个方法会更好?

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

3 个答案:

答案 0 :(得分:11)

你不应该为自己太难。所有你需要的是用应用了所需样式的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 );

以上示例导致:

enter image description here

答案 1 :(得分:3)

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

答案 2 :(得分:2)

我不会使用SQL方法。随着时间的推移,你有越来越多的突出规则,这将变得无法管理。处理需要以foo突出显示foobar而不是{{1}}的情况更为棘手,但其中一个包含另一个。

将数据处理与格式分开。