SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Addict crabby80's Avatar
    Join Date
    May 2007
    Posts
    387
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    maintaining case of highlighted text from search

    Hi guys

    I'm using this script to highlight words that the user searched for. I done it so it's not case dependent. But, doing it this way, if the user searches 'dog' it will find 'Dog' and replace it with <span id="hightlight>dog</span> (title case to lowercase). What's the best way to resolve this?

    Any help would be much appreciated

    Crabby

  2. #2
    SitePoint Wizard
    Join Date
    Nov 2005
    Posts
    1,191
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I done it so it's not case dependent.
    Do it so it is?? What's the script.

  3. #3
    SitePoint Addict crabby80's Avatar
    Join Date
    May 2007
    Posts
    387
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    LOL, jees don't you just hate Monday mornings, script is now below!!

    Client does't want it to be case dependent, so if they search dog, Dog will be found

    PHP Code:
    $manual_text file_get_contents(DIR_INCLUDES 'manual.php');

    if(isset(
    $_POST['search']))
    {
        
    $keywords = array();
        
        if(!empty(
    $_POST['keywords']))
        {
            
    $keywords explode(',',$_POST['keywords']);
        }
        
        foreach(
    $keywords as $keyword)
        {
            
    $manual_text str_ireplace($keyword,'<span class="highlight">'.$keyword.'</span>',$manual_text);
        }


  4. #4
    SitePoint Wizard
    Join Date
    Nov 2005
    Posts
    1,191
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    nvm

  5. #5
    SitePoint Member
    Join Date
    May 2006
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You need to use a regular expression to wrap the word as it appears in the original text, not as it appears in your keyword list.

    PHP Code:
    foreach($keywords as $keyword)
    {
        
    $manual_text preg_replace('/(' $keyword ')/i''<span class="highlight">$1</span>'$manual_text);

    One improvement would be to ensure it only matches whole words, i.e. not highlight the letters if they appear in the middle of another word. You can do this using word boundaries in your expression:

    PHP Code:
    $manual_text preg_replace('/\b(' $keyword ')\b/i''<span class="highlight">$1</span>'$manual_text); 


Bookmarks

Posting Permissions

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