How to emphasize specific words from a string (text)

Posted on September 6, 2008, Filled under PHP,  Bookmark it

Thanks for visiting our website! We regularly publish posts like this one. If you are interested in receiving the latest updates as soon as they are posted, please consider subscribing to the RSS feed or to our e-mail newsletter.

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:

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.

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!

Get our RSS Feed!

Sponsors

Related Posts

Leave a Reply


* = required fields

(will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


  

CommentLuv Enabled