Jump to content

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");
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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