Jump to content

Highlight Function Issue


Canman2005

Recommended Posts

Hi all

 

I have the following function code to highlight text on a page

 

function highlight_words($str, $keywords = '')
{
$keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords)));
$style = 'highlight';
$var = '';
foreach(explode(' ', $keywords) as $keyword)
{
$replacement = '<span class="highlight">'.$keyword.'</span>';
$var .= $replacement." ";
$str = eregi_replace($keyword, $replacement, $str);
}
print eregi_replace(rtrim($var), '<span class="highlight">'.$keywords.'</span>', $str);
}

 

and I use the function like

 

<?php highlight_words(''.$row_contents['title'].'',''.$_GET['q'].''); ?>

 

this works fine, but I have found an issue.

 

Basically I have a entry in my database titled

 

get a quote

 

If I use my highlight function and set the value of $_GET['q'] as

 

?q=get+a

 

then

 

Instead of simply doing

 

<span class="highlight">get</span> <span class="highlight">a</span> quote

 

like it should, it returns instead

 

<sp><span class="highlight">a</span>n cl<span class="highlight">a</span>ss="highlight">get</sp><span class="highlight">a</span>n> <span class="highlight">a</span> quote

 

Any ideas why this is happening?

 

Looks like it's treating the html tags are text to highlight

 

Any help would be magic

 

Thanks

 

Mark

Link to comment
https://forums.phpfreaks.com/topic/183568-highlight-function-issue/
Share on other sites

Yes, it is finding "a" inside of the html code that you are adding for each additional keyword. One way around this is to make a string (or character) that is unlikely to occur to mark each area as being ready to highlight:

<?php
function highlight_words($str, $keywords = '')
{
   $keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords)));
   $keywords = explode(' ', $keywords);
   foreach($keywords as $i => $keyword)
      $keywords[$i] = "/(".$keyword.")/";
      
   $str = preg_replace($keywords, '{[:[|$1|]:]}', $str);
   return preg_replace("/{\[:\[\|(.+?)\|\]:\]}/", '<span class="highlight">$1</span>', $str);
}

echo highlight_words("get a quote", "get a");
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.