Jump to content

Highlighting function


Matpatnik
 Share

Recommended Posts

Can someone help me with this function.

$haystack = 'this is a test to testing this test.';$needle01 = 'this';$needle02 = 'is';$needle03 = 'a';$needle04 = 'test';### highlighting ###function highlight($haystack,$needle01,$needle02='',$needle03='',$needle04='') {	$haystack = explode(' ',$haystack);	$countstr = count($haystack);	for ($i=0;$i<$countstr;$i++) {		if (stristr($haystack[$i],$needle01) == true) {			$replace = '<span class="highlightyellow">'. $haystack[$i] .'</span> ';			$string[$i] = str_ireplace($needle01, $replace, $haystack[$i]);		} else if (stristr($haystack[$i],$needle02) == true) {			$replace = '<span class="highlightgreen">'. $haystack[$i] .'</span> ';			$string[$i] = str_ireplace($needle02, $replace, $haystack[$i]);		} else if (stristr($haystack[$i],$needle03) == true) {			$replace = '<span class="highlightred">'. $haystack[$i] .'</span> ';			$string[$i] = str_ireplace($needle03, $replace, $haystack[$i]);		} else if (stristr($haystack[$i],$needle04) == true) {			$replace = '<span class="highlightblue">'. $haystack[$i] .'</span> ';			$string[$i] = str_ireplace($needle04, $replace, $haystack[$i]);		} else {			$string[$i] = $haystack[$i];		}	}			echo implode(' ',$string);}

return the source:

<span class="highlightyellow">this</span> <span class="highlightgreen">is</span> <span class="highlightred">a</span> <span class="highlightblue">test</span> to <span class="highlightblue">testing</span> ing <span class="highlightyellow">this</span> <span class="highlightblue">test.</span> .

I don't know why it double the 'ing' and '.'.

Link to comment
Share on other sites

Your needle is "test", you split up the string into words and check if each word contains any needle. Then you replace the needle with the higlighted string. You need to replace the entire word, not just the needle. So it sees "testing" and replaces the "test" part only with the highlighted text, leaving the "ing".

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...