Jump to content

Google-Like highlighting


pantinosm

Recommended Posts

if there is code that exists, there is no doubt that you will have to modify it at least a little bit to get it to work with your script. to get it working properly, you're probably going to want to know how to use regex. it's not going to work like plug-n-play.

I use this script here which someone gave to me.

<?php 
function highlight($str) {
$tmp = '';


foreach(explode(' ', $str) as $word)
$tmp .= "<span style=\"background-color:pink\">$word</span> ";

return trim($tmp);

}
?>

 

This function runs when i call echo preg_replace("/$searchterm/ise", 'highlight("\\0")',  $result);

 

The problem is that not all keywords are highlighted. It leaves many words back. Sometimes ithighlights, sometimes no. Why is this happenning?

pantinosm,

 

I couldn't get your code to work... Using your preg_replace function had a parsing error ( Delimiter must not be alphanumeric or backslash ).

 

Also, I could never get it to call your highlight function... Don't have a clue why not.  :-\

 

So, I played around with your concept a bit, and came up with the following generic highlight function.

 

Scot L. Diddle, Richmond VA

 

highlightString.php

 


<?php

require_once('include/wordHighlight.php');

	$string = 'Now is the time for all good programmers... etc';	
highlight("$string", "programmers");

echo $highlightedString;

?>

 

wordHighlight.php

 


<?php 

function highlight($str, $slectedWord)  {

	global $highlightedString; 

	$highlightedString = '';

	foreach(explode(' ', $str) as $word) {

		$currentWordLength = strlen($word);

		$lastChar = substr($word,$currentWordLength-1) . ' ';			

		if (substr($word,$currentWordLength-2,2) == '..' ) {
			$lastChar = '..';
		}

		if (substr($word,$currentWordLength-3,3) == '...' ) {
			$lastChar = '...';
		}			


		$word =  str_replace(',', ' ', $word); // replace , by space
		$word =  str_replace('.', ' ', $word); // replace . by space
		$word =  str_replace('?', ' ', $word); // replace ? by space
		$word =  str_replace(':', ' ', $word); // replace ? by space
		$word =  str_replace('!', ' ', $word); // replace ? by space
		$word = trim($word);

	    if  ($word == $slectedWord) {
		$highlightedString .= ' ' . "<span style=\"background-color:pink\">$word</span>$lastChar";
	    }
	    
	  else {
		  
		$highlightedString .= ' ' . $word;

	  }

	}

	return trim($highlightedString);

}


?>

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.