How to emphasize specific words from a string (text)
Posted on September 6, 2008, Filled under PHP,
Bookmark it
This function can help you to emphasize specific words from a simple (non-html) text. You can currently choose between 3 ways of emphasis: bold, underline, highlight. You can also add your own method of emphasis if you add more ELSE IFs with the ‘type’ and ‘css property’.
<?php
/*
---------------------------------------
Credits: Bit Repository
URL: http://www.bitrepository.com/
---------------------------------------
*/
function emphasize_specific_words($str, $words, $type = 'highlight')
{
if($type == 'highlight')
{
$var_style = 'background: #CEDAEB;';
}
else if($type == 'bold')
{
$var_style = 'font-weight: bold;';
}
else if($type == 'underline')
{
$var_style = 'text-decoration: underline;';
}
if(is_array($words))
{
foreach($words as $word)
{
if(strlen($word) <= 1)
{
continue;
}
if($word)
{
$word= strip_tags($word);
$word= preg_quote($word, '/');
$str = preg_replace('/'.$word.'/i',
"<span style='".$var_style."'>".$word."</span>",$str);
}
}
return $str;
}
else
{
return false;
}
}
$str = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Sed id eros sit amet lorem consectetuer volutpat.
Ut egestas congue magna. Lorem ipsum dolor sit amet,
consectetuer adipiscing elit.
Nunc sapien. Quisque fermentum dui sed velit. Nulla eget eros.
Cras tristique vulputate sapien.";
# Words to emphasize (should be an array)
$words = array('Lorem', 'consectetuer', 'amet',
'fermentum', 'tristique', 'vulputate');
# 1st argument: the text
# 2nd argument: the keywords array
# 3rd argument: the type of emphasis (bold, underline, highlight)
// tags from $words are automatically stripped
$string = emphasize_specific_words($str, $words, 'bold');
echo $string;
?>
Here's the output of our example:
Sed id eros sit amet Lorem consectetuer volutpat.
Ut egestas congue magna. Lorem ipsum dolor sit amet,
consectetuer adipiscing elit.
Nunc sapien. Quisque fermentum dui sed velit. Nulla eget eros.
Cras tristique vulputate sapien.
You can also check our keywords highlighter if you want to highlight your keywords in your search results.
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- September 6, 2008
- article by Gabriel C.
- Leave a reply!
Related Posts
Highlight (Search) Key Words in a Text | PHPat August 30, 2008 with 8 comments
PHP: Randomize Text Letters while Keeping the Words Readableat October 4, 2008 with 3 comments
How to Create an Advanced PHP (bad, naughty) Words Filterat October 26, 2008 with 6 comments
Shorten a string (text)at September 3, 2008 with 2 comments
Format text into a SEO Friendly Stringat August 28, 2008 with 1 comment
