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 4 of 4
  1. #1
    New Coder
    Join Date
    Jun 2012
    Posts
    47
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Trying to highlight the complete search phrase only in search results

    I am using the following function to highlight the results of a database search.
    Currently things are working fine the words used in the search are highlighted
    within the paragraph or so retrieved from the database however if I search for
    "the words" the highlighting is applied to the "the words" plus each instance of "the"
    or "words". I would like to highlight only the complete phrase whether it includes
    one word or a few.
    The problem persists even though the regex used in the function has \b boundaries specified,
    also is there a way to achieve this by making the regex non-greedy in some way?


    PHP Code:
    function highlight($text$search) {    
    preg_match_all('@\[email protected]'$search$m);   
     if(!
    $m)  
    return 
    $text;      
     
    $re '@\\b(' implode('|'$m[0]) . ')\\[email protected]';    
    return 
    preg_replace($re'<i class="hightlighttext">$0</i>'$text);}

    echo 
    highlight($text,$search); 

  2. #2
    Senior Coder djm0219's Avatar
    Join Date
    Aug 2003
    Location
    North Carolina
    Posts
    1,540
    Thanks
    4
    Thanked 245 Times in 242 Posts
    How about using str_ireplace instead of preg_match_all and preg_replace?

    PHP Code:
    function highlight($text$search) {    
        return 
    str_ireplace($search,'<i class="hightlighttext">' $search '</i>',$text);

    Dave .... HostMonster for all of your hosting needs

  3. #3
    New Coder
    Join Date
    Jun 2012
    Posts
    47
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks, the new function works great.
    It seems a straight forward replacement, for what looked to me, quite complicated bit of code.

    In the quest to become a better coder, could you possibly give me a quick break down of what
    was going on in the previous function.

    Thanks again for all of your help.

  4. #4
    Senior Coder djm0219's Avatar
    Join Date
    Aug 2003
    Location
    North Carolina
    Posts
    1,540
    Thanks
    4
    Thanked 245 Times in 242 Posts
    Sorry but I don't use preg_match or preg_replace. Haven't met a situation yet that couldn't be taken care of with other methods.
    Dave .... HostMonster for all of your hosting needs


 

Tags for this Thread

Posting Permissions

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