Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-18-2007, 12:15 AM   PM User | #1
glz
New Coder

 
Join Date: Apr 2007
Posts: 57
Thanks: 3
Thanked 0 Times in 0 Posts
glz is an unknown quantity at this point
highlighting text in html with regex

Code:
<?php
$pat = '/hello (h)ow are y(o)u/';
$haystack = 'hello how are you doing today?';
preg_match_all($pat, $haystack, $out);
print_r($out);
?>
outputs:
Code:
Array
(
    [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
glz is offline   Reply With Quote
Old 12-19-2007, 10:34 PM   PM User | #2
glz
New Coder

 
Join Date: Apr 2007
Posts: 57
Thanks: 3
Thanked 0 Times in 0 Posts
glz is an unknown quantity at this point
solved! It was quite a challenge, shame none of you stepped up to it.

Proof of Concept:
http://nancywalshee03.freehostia.com...Saved=657numqu


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!
glz is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 02:00 AM.


Advertisement
Log in to turn off these ads.