note 83666 deleted from function.str-ireplace by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 14:52:58 +0000 |
| Subject: | note 83666 deleted from function.str-ireplace by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155681@lists.php.net to get a copy of this message | ||
Note Submitter: jgriggs777 at yahoo dot com
----
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");
?>