Blorner

Friday, November 27, 2009

Highlight words in a text

This function is used to search and highlight words from the text.

function highlight_words($text,$word){
$text = preg_replace('/\b'.$word.'\b/i', '<span class="highlight">$0</span>', $text);
return $text;
}


Note to that if the searched word is in the structure of the other wordform (for example the word "stand" is in the structure of the word "understand"), so the word will not be highlighted. It will be highlighted when after or before the word is not appeared alphabetic or digital character or underline (_) character. The function also ignores case sensitivity of the word. If the searched word is "light", the words "highlight", "light_faced", "lighten", "light9" e.t.c. will not be highlighted as well.

Example:


Searching the word "book" in the text "Our book-keeper was bought an interesting book from bookshop. Book name is My big book."

<?php
function highlight_words($text,$word){
$text = preg_replace('/\b'.$word.'\b/i', '<span class="highlight">$0</span>', $text);

return $text;
}?>


<style>
.highlight{
background-color: #214579;
color: #ffffff;
}
</style>
<?php
$word = "book";
$text = "Our book-keeper was bought an interesting book from bookshop. Book name is My big book.";

echo(highlight_words($text,$word));
?>

The above example will output:

Our book-keeper was bought an interesting book from bookshop. Book name is My big book.

You see that the word "book" of the wordform "bookshop" was not highlighted, and the words "book-keeper", "book", "Book" and "book" which is followed by the punctuation mark "." was highlighted.

Set your style to the highlighted words in .highlight{ ... }.

The demo you can see here.

No comments:

Post a Comment

Art Works Expo