如何突出搜索结果 [英] how to highlight search results

查看:115
本文介绍了如何突出搜索结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



所以我有这个搜索代码:

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

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

foreach($关键字为$ key => $关键字){
$ where2。=`column` LIKE'%$ keyword%'';
$ b $ if if($ key!=($ total_keywords - 1)){
$ where2。=OR;



$ result_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)){
$ b $ returned_results [] = array(
'ab'= > $ row ['ab'],
'cd'=> $ row ['cd'],
);
}

return $ returned_results;
}
}
?>

并希望在其中实现第二个功能:

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

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

$ c = 0;

foreach($ words为$ 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;
}
}
返回$ text;
}

$示例=< 一些文本在
EOT里面;

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

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

所以我有这个代码不起作用:

 <?php 
函数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($关键字为$ key => $关键字){

$ regexp =/($ w)(?![^ <+] )/一世;
$ 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%';
$ b $ if if($ key!=($ total_keywords - 1)){
$ where2。=OR;


$ b $ result_text =SELECT`a`,LEFT(`b`,150)为`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)){
$ b $ returned_results [] = array(
'ab'= > $ row ['a'],
'cd'=> $ row ['b'],
);
}

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

当我寻找它的时候,我发现了两种可能性。第一个是第二个将直接从select查询中突出显示的函数:

  SELECT 
REPLACE( ````````````````````` col` LIKE%foobar%

所以我的问题是如何实现第二个函数到搜索功能,还是会更好地使用第二种方法?



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

解决方案

你不应该为自己付出太多的代价。所有你需要的是用所需要的样式代替span中包含的单词。这应该适合你:

 函数highlight_word($ content,$ word,$ color){
$ replace = '< span style =background-color:'。$ color。';>'。 $字。 < /跨度>; //创建替换
$ content = str_replace($ word,$ replace,$ content); //替换内容

return $ content; //返回突出显示的数据
}

函数highlight_words($ content,$ words,$ colors){
$ color_index = 0; //颜色索引(假设它是一个数组)

//循环单词
foreach($ words为$ word){
$ content = highlight_word($ content,$字,$颜色[$ color_index]); //突出显示单词
$ color_index =($ color_index + 1)%count($ colors); //获取下一个颜色索引
}

return $ content; //返回突出显示的数据
}



//单词查找
$ words = array(
'normal',
'text'
);

//颜色使用
$ colors = array(
'#88ccff',
'#cc88ff'
);

//伪造你的results_text
$ results_text = array(
array(
'ab'=>'AB#1',
'cd '=>'一些普通单词的普通文本根本不会异常'
),array(
'ab'=>'AB#2',
'cd '=>'这是另一个包含非常普通内容的文本'

);

//循环结果(假设$ output1为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>< /字段集>;
}

使用正则表达式替换内容也可以,但使用 str_replace()有点快。



函数接受这些参数:

highlight_word(string,string,string);



highlight_words(string ,array,array);



以上例子的结果是:

< img src =https://i.stack.imgur.com/AUUtp.pngalt =在这里输入图片描述>


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
        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. 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.

The functions accepts these arguments:

highlight_word( string, string, string );

highlight_words( string, array, array );

The above example results in:

这篇关于如何突出搜索结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆