Highlight text for search results in PHP

Useful code to highlight text occurences in search results or in a text. How to highlight text in a string…

September 2, 2016

Useful code to highlight text occurences in search results or in a text. How to highlight text in a string with PHP and regular expression? Here is the solution:

// highlight text in a string
function highlight($text_highlight, $text_search) {
$str = preg_replace('#'. preg_quote($text_highlight) .'#i', '<span style="background-color:#FFFF66; color:#FF0000;">\\0</span>', $text_search);
return $str;
}

Author

I’m a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I’m the founder of Rockit.it and Dailybest.it and I’m actually the Chief Technical Officer of Better Days web agency.


Recommended

How to add rel=”nofollow” to links with preg_replace()

Adding rel="nofollow" to external link is a good SEO practice.

September 22, 2015

Block junk emails, spammers and temporary emails

If you need an Email Validator Function, consider this version that includes also the check against common temporary mail services…

December 3, 2013

How many times a web link has been shared on Twitter

Twitter share button and Facebook share button are the most used buttons to share links on Internet. You can read…

October 19, 2012

get MySpace events with a PHP function

Here is a function to read the concerts for a myspace band page. This code retrieves the “shows page” for…

February 21, 2011

Limit the number of categories for posts in WordPress

CHOOSE ONLY ONE CATEGORY WORDPRESS If you need to limit the number of categories used by the authors of your…

September 14, 2015

Reordering rows records on a mysql table with PHP

This PHP function lets you reorder records on a table when you have a field used for save the position.…

December 18, 2013