php - 如何突出显示搜索结果

标签 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
        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(字符串, 字符串, 字符串);

highlight_words(字符串,数组,数组);

上面的例子导致:

enter image description here

关于php - 如何突出显示搜索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10313332/

相关文章:

html - 是否可以将自定义按钮添加到 mat select 下拉列表中?

mysql - 在mysql中创建记录

php - 表单数据未发送到 MySql 数据库

mysql外键不起作用

javascript - Chrome/Windows 7 上 JavaScript 的 Alt 键行为?

php - 使用 PHP 和 MySQL 开发 'Quiz' Web 应用程序的数据库设计

php - 执行另一个 PHP 文件并返回方法的输出,这可能吗?

php - CDbException CDbConnection.connectionString 不能为空

php - 为 Windows 上的初学者 PHP 程序员推荐的工具?

css - float 嵌套 div 的填充高度