About

You’re visiting the personal website of Joost Schuttelaar.

Take a look

Contact

You can e-mail me at jelephants @ jstsch.com (anti-spam: please remove the mammal with the big snout).

Twitter feed @jstsch

Sorry, feed is gone. API has been killed by Twitter.

Recent posts

PHP: Highlighting words in a string

Monday March 7 2011

Seemingly simple things are often hard. How about a function which takes a text, an array of keywords and a max length, and outputs a highlighted string up to that max length? The highlighted string should be in the middle of the returned segment, of course.

In PHP, it becomes a bit of a mess because of its multibyte Unicode handling. I noticed that most frameworks don’t take care of our fâncy European characters correctly, so I had to roll my own.

The following set of functions handle it, although mb_ereg will probably be deprecated soon. Bonus points for who converts this to use preg (with the /u modifier). Back when I wrote this most PHP installs weren’t precompiled with the correct PCRE lib.

Hope it helps someone!

highlight.php

Comments


(never shown, not required)
(not required)