View Full Version : highlighting text in html with regex

12-18-2007, 12:15 AM
$pat = '/hello (h)ow are y(o)u/';
$haystack = 'hello how are you doing today?';
preg_match_all($pat, $haystack, $out);

[0] => Array
[0] => hello how are you

[1] => Array
[0] => h

[2] => Array
[0] => o


I want to output the original haystack and highlight the full pattern match red and highlight the substring pattern matches green, so my output should be this:

<font color="red">hello <font color="green">h</font>ow are y<font color="green">o</font>u</font> doing today?

How can I do this in php code? This has been boggling me for a while.
Note: preg_replace() replaces the full pattern not the substrings

Thank you

12-19-2007, 10:34 PM
solved! It was quite a challenge, shame none of you stepped up to it. :)

Proof of Concept:

Note to anyone else attempting this:
preg_match_all() does indeed output the offsets of all substrings and full matches with the PREG_OFFSET_CAPTURE flag, you can use this to your advantage...

Thanks glz!
glz: no problem! :)