[Your IP: 23.20.25.122]
Logowanie

Język: PL EN

KySoft Systemy Informatyczne


sitemap

PHP/HTML tips & tricks

email-validator
html-entities
http-build-str
inline-sms-orange
inline-youtube
mathjax-equations
rss-howto
skype-hidden-emots
syntax-highlight
text-highlight
world-flags
(currently only in english)

Highlight text on given keywords


Simple method with str_replace.
Replaces source keywords, not extendable
function str_highlight($txt,$words){
	if (!is_array($words)){
		$words=preg_split("/[^[:alpha:]]+/",$words);
		$words=array_unique($words);
	}
	$repl=array();
	for ($i=0; $i<sizeof($words); ++$i)
		$repl[$i]="<span class=\"hi\">".$words[$i]."</span>";
	return str_ireplace($words,$repl,$txt);
}

More generic method with preg_replace.
Keeps source keywords as is though match is case insensitive.
Easly extendable to support any regex matching
function highlight($txt,$words){
	if (!is_array($words)){
		$words=preg_split("/[^[:alpha:]]+/",$words);
		$words=array_unique($words);
	}
	$regex="";
	for ($i=0; $i<sizeof($words); ++$i)
		$regex.="|(".$words[$i].")";
	$regex=substr($regex,1);
	return preg_replace("#(".$regex.")#si","<span class=\"hi\">\$1</span>",$txt);
}


Dodaj komentarz