# Show the Matching Text in Search Results

> Replaces the usual opening-lines excerpt in search results with the passage of the post that actually contains the search words.

- Type: PHP
- Runs: Run everywhere
- Category: [Search](https://wpide.com/library/category/search/)
- Tags: search, excerpts, results
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/search-excerpt-around-match/

## Code

```php
add_filter( 'get_the_excerpt', function ( $excerpt, $post = null ) {
    if ( is_admin() || ! is_search() || ! in_the_loop() || ! $post || ! function_exists( 'mb_stripos' ) ) {
        return $excerpt;
    }

    $terms = array_filter( preg_split( '/\s+/', trim( (string) get_search_query( false ) ) ), function ( $term ) {
        return mb_strlen( $term ) > 2;
    } );

    if ( ! $terms ) {
        return $excerpt;
    }

    $text = trim( preg_replace( '/\s+/u', ' ', wp_strip_all_tags( strip_shortcodes( excerpt_remove_blocks( $post->post_content ) ) ) ) );

    foreach ( $terms as $term ) {
        $position = mb_stripos( $text, $term );

        if ( false === $position ) {
            continue;
        }

        $start   = max( 0, $position - 100 );
        $passage = mb_substr( $text, $start, 260 );

        if ( $start > 0 ) {
            $passage = preg_replace( '/^\S*\s/u', '', $passage );
        }

        if ( $start + 260 < mb_strlen( $text ) ) {
            $passage = preg_replace( '/\s\S*$/u', '', $passage );
        }

        return ( $start > 0 ? '&hellip; ' : '' ) . esc_html( $passage ) . ( $start + 260 < mb_strlen( $text ) ? ' &hellip;' : '' );
    }

    return $excerpt;
}, 20, 2 );
```

## Notes

Combine it with the Highlight Search Terms snippet to mark the words inside the passage.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Show the Matching Text in Search Results" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
