简体   繁体   中英

Highlight keyword on search results php

I am trying to make any keyword bold when the user types the current keyword.

I have this code and it is working fine.

for($k=$no_words; $k>0 ;$k--) {

            $w=trim($search_array[$k-1]);
            if($w!='')
            {
                $result[$i]['title'] = preg_replace('/(' . preg_quote($search_array[$k-1], '/') . ')/siU', '<b>\\1</b>', $result[$i]['title']);
                $result[$i]['description'] = preg_replace('/(' . preg_quote($search_array[$k-1], '/') . ')/siU', '<b>\\1</b>', $result[$i]['description']);
            }
        }

My problem is as follows:

I have this keyword: this is my keyword

When I type: " this is my keyword " I get this result: " this is my keyword "

But when I type: " This is keyword " I get this result: "this is my keyword" without the words in the result being bolded.

What I doing wrong?

I suppose you need following:

$search_array = array_unique(explode(' ', $search));
foreach ($search_array as $k => $v)
{
    $w = trim($v);
    if ($w)
    {
        $result[$i]['title'] = preg_replace('/(' . preg_quote($w, '/') . ')/siU', '<b>\\1</b>', $result[$i]['title']);
        $result[$i]['description'] = preg_replace('/(' . preg_quote($w, '/') . ')/siU', '<b>\\1</b>', $result[$i]['description']);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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