Matpatnik Posted December 9, 2007 Share Posted December 9, 2007 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 More sharing options...
justsomeguy Posted December 10, 2007 Share Posted December 10, 2007 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 More sharing options...
Matpatnik Posted December 11, 2007 Author Share Posted December 11, 2007 I see thanks a lot Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.