Return to Snippet

Revision: 22520
at January 14, 2010 06:38 by giak


Initial Code
/*
neo_highlight_keywords(string $text, array $keywords, string $tag_start, string $tag_end)  
use : echo neo_highlight_keywords($text, $keywords, '<span>', '</span>');
$keywords between $tag_start and $tag_end
better match with function neo_remove_accent()
*/
function neo_highlight_keywords($text, $keywords, $tag_start, $tag_end){
	$original 	= $text;
	$text 		= strtolower($text); // can use with function neo_remove_accent($text)
	$tagLen 	= (strlen($tag_start) + strlen($tag_end));
 
	foreach($keywords as $keyword){		
		$keyword	= strtolower($keyword); // can use with function neo_remove_accent($text)
		$current	= $offset = $delta = 0; 
		$len 		= strlen($keyword);
		 
		while(( FALSE !== ($pos = strpos($text, $keyword, $offset)))){
			$original	= substr($original, 0, ($pos + $delta))
						.$tag_start.substr($original, ($pos + $delta), $len).$tag_end
						.substr($original, ($pos + $delta + $len));
			
			$delta		+= $tagLen; // Add String Tags Lenght
			$offset		= $pos + 1;
			}
		} 
	return $original;
}

Initial URL
http://www.giacomel.fr

Initial Description

                                

Initial Title
PHP : highlight keywords in a text

Initial Tags
array

Initial Language
PHP