@'), array(' ', "\n"), apply_filters('the_content', $post->post_content))) : ''); // Search content for terms $terms = $wp_query->query_vars['search_terms']; if ( preg_match_all('/'.str_replace('/', '\/', join('|', $terms)).'/i', $content, $matches, PREG_OFFSET_CAPTURE) ) { $padding = max($min_padding, $max_length / (2*count($matches[0]))); // Construct extract containing context for each term $output = ''; $last_offset = 0; foreach ( $matches[0] as $match ) { list($string, $offset) = $match; $start = $offset-$padding; $end = $offset+strlen($string)+$padding; // Preserve whole words while ( $start > 1 && preg_match('/[A-Za-z0-9\'"-]/', $content{$start-1}) ) $start--; while ( $end < strlen($content)-1 && preg_match('/[A-Za-z0-9\'"-]/', $content{$end}) ) $end++; $start = max($start, $last_offset); $context = substr($content, $start, $end-$start); if ( $start > $last_offset ) $context = '...'.$context; $output .= $context; $last_offset = $end; } if ( $last_offset != strlen($content)-1 ) $output .= '...'; } else { $output = $content; } if ( strlen($output) > $max_length ) { $end = $max_length-3; while ( $end > 1 && preg_match('/[A-Za-z0-9\'"-]/', $output{$end-1}) ) $end--; $output = substr($output, 0, $end) . '...'; } // Highlight matches $context = nl2br(preg_replace('/'.str_replace('/', '\/', join('|', $terms)).'/i', '$0', $output)); ?>

Read this entry