note 83666 added to function.str-ireplace

From: Date: Fri, 06 Jun 2008 14:27:51 +0000
Subject: note 83666 added to function.str-ireplace
Groups: php.notes 
Request: Send a blank email to php-notes+get-140182@lists.php.net to get a copy of this message
My apologies. I'm a PHP newbie and the count function on my script below didn't work right if you have more than one "keyword". I searched and spent a long time to get this to work right, so wanted to share it. This is very easy to use by doing the following. $text - is the text to search $words - are the words to highlight (search text) $the_place - is so that you can tell your users what "area" was searched. <?php function highlight_this($text, $words, $the_place) { $words = trim($words); $the_count = 0; $wordsArray = explode(' ', $words); foreach($wordsArray as $word) { if(strlen(trim($word)) != 0) //exclude these words from being replaced $exclude_list = array("word1", "word2", "word3"); // Check if it's excluded if ( in_array( strtolower($word), $exclude_list ) ) { } else { $text = str_ireplace($word, "<span class=\"highlight\">".strtoupper($word)."</span>", $text, $count); $the_count = $count + $the_count; } } //added to show how many keywords were found echo "<br><div class=\"emphasis\">A search for <strong>" . $words. "</strong> found <strong>" . $the_count . "</strong> matches within the " . $the_place. ".</div><br>"; return $text; } //example of how to use $text_to_highlight = highlight_this($text_to_highlight, $search_text, "Place you searched"); ?> ---- Server IP: 64.71.164.2 Probable Submitter: 66.76.96.68 ---- Manual Page -- http://www.php.net/manual/en/function.str-ireplace.php Edit -- https://master.php.net/note/edit/83666 Del: integrated -- https://master.php.net/note/delete/83666/integrated Del: useless -- https://master.php.net/note/delete/83666/useless Del: bad code -- https://master.php.net/note/delete/83666/bad+code Del: spam -- https://master.php.net/note/delete/83666/spam Del: non-english -- https://master.php.net/note/delete/83666/non-english Del: in docs -- https://master.php.net/note/delete/83666/in+docs Del: other reasons-- https://master.php.net/note/delete/83666 Reject -- https://master.php.net/note/reject/83666 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#140182) next »