Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    glz
    glz is offline
    New Coder
    Join Date
    Apr 2007
    Posts
    57
    Thanks
    3
    Thanked 0 Times in 0 Posts

    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

  • #2
    glz
    glz is offline
    New Coder
    Join Date
    Apr 2007
    Posts
    57
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •