Trim the search result around the search word

I want to trim my search results page down to 20 words before and 20 words after the highlighted search word. I am getting accurate search results and the search word is highlighting. I have tried variations with
wp_trim_words();
such as:

            $trimmed_content = wp_trim_words( $searchresults, 25, NULL );
              echo $trimmed_content;

but what I so far cannot get and what I want is a search result that trims 20 words before and after the highlighted search word. My ‘search.php’ page code is:

    <div class="searchresultsbox"> 
    <?php if(have_posts()):while (have_posts()):the_post();?>
    <a href="https://wordpress.stackexchange.com/questions/274268/<?php the_permalink(); ?>">
    <h3 class="title-heading"><?php the_title(); ?></h3>         
    </a>    
    <?php 
      $searchresults = $post->post_content;
      $highlightword = get_search_query();
      $searchresults = str_replace($highlightword, 
      '<span style="background-color:#ffff00;">'.$highlightword.'</span>',
      $searchresults);

      echo $searchresults;

      endwhile;
      else: echo "No matching result found";
      endif;
      ?>  
      </div><!-- /searchresultsbox -->
    </div><!-- /collcelltwo -->
  </div><!-- /tb-one-row --> 
</div><!-- /tb-one -->

Many thanks to Rick Hellewell for the “str_replace” function which highlights the search word. Thank you for the help.

1 Answer
1

A random thought: put the search string into an array ( with explode). Find the array position of the highlighted string. Count back xx for the start, and forward xx for the end. Extract those array values, then implode them back into a string.

That would work for one searchresult word in the string. You’d have to loop through multiple occurrences of the searchresult word.

Say the full search result has 200 words. The searchresult word is at position 50. Extract words starting at 30 and ending at 70. Put the words back into one string. Show the string.

Might be a better way, though, but that was my first thought.

Leave a Comment