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…

Settembre 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

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.

Recommended

WP doesn’t send email? try this

Snippets for sending emails with Wordpress

Febbraio 8, 2020

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

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

Settembre 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…

Dicembre 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…

Ottobre 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…

Febbraio 21, 2011

ASP equivalent to PHP strip_tags

I’ve found those functions around in the internet and I put them here just to remind how to strip tags…

Febbraio 9, 2010