Limit WP excerpt to second sentence

I use this function to limit my WP expiration to a sentence, and not just turn it off after a few words.

add_filter('get_the_excerpt', 'end_with_sentence');

function end_with_sentence($excerpt) {
  $allowed_end = array('.', '!', '?', '...');
  $exc = explode( ' ', $excerpt );
  $found = false;
  $last = '';
  while ( ! $found && ! empty($exc) ) { 
    $last = array_pop($exc);
    $end = strrev( $last );
    $found = in_array( $end{0}, $allowed_end );
  }
  return (! empty($exc)) ? $excerpt : rtrim(implode(' ', $exc) . ' ' .$last);
}

It works like a charm, but I would like to limit it to two sentences. Does anyone have an idea how to do this?

+4
source share
2 answers

Your code didn’t work for me in 1 sentence, but hey 2am here, maybe I missed something. I wrote this from scratch:

add_filter('get_the_excerpt', 'end_with_sentence');

function end_with_sentence( $excerpt ) {
  $allowed_ends = array('.', '!', '?', '...');
  $number_sentences = 2;
  $excerpt_chunk = $excerpt;

  for($i = 0; $i < $number_sentences; $i++){
      $lowest_sentence_end[$i] = 100000000000000000;
      foreach( $allowed_ends as $allowed_end)
      {
        $sentence_end = strpos( $excerpt_chunk, $allowed_end);
        if($sentence_end !== false && $sentence_end < $lowest_sentence_end[$i]){
            $lowest_sentence_end[$i] = $sentence_end + strlen( $allowed_end );
        }
        $sentence_end = false;
      }

      $sentences[$i] = substr( $excerpt_chunk, 0, $lowest_sentence_end[$i]);
      $excerpt_chunk = substr( $excerpt_chunk, $lowest_sentence_end[$i]);
  }

  return implode('', $sentences);
}
+1
source

I see the complexities in your code example that make it (possibly) harder than it should be.

. , : https://regex101.com/

preg_split()

function end_with_sentence( $excerpt, $number = 2 ) {
    $sentences = preg_split( "/(\.|\!|\?|\...)/", $excerpt, NULL, PREG_SPLIT_DELIM_CAPTURE);

    var_dump($sentences);

    if (count($sentences) < $number) {
         return $excerpt;
    }

    return implode('', array_slice($sentences, 0, ($number * 2)));
}

$excerpt = 'Sentence. Sentence!  Sentence? Sentence';

echo end_with_sentence($excerpt); // "Sentence. Sentence!"
echo end_with_sentence($excerpt, 1); // "Sentence."
echo end_with_sentence($excerpt, 3); // "Sentence. Sentence!  Sentence?"
echo end_with_sentence($excerpt, 4); // "Sentence. Sentence!  Sentence? Sentence"
echo end_with_sentence($excerpt, 10); // "Sentence. Sentence!  Sentence? Sentence"
+1

Source: https://habr.com/ru/post/1622606/


All Articles