将WP摘录限制为第二句

时间:2016-01-03 13:32:00

标签: php wordpress

我使用此功能将我的WP摘录限制为一个句子,而不是仅仅在一些单词之后将其删除。

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);
}

像魅力一样,但我想将其限制为两句话。任何人都知道如何做到这一点?

2 个答案:

答案 0 :(得分:1)

你的代码对我来说不适用于1句话,但是嘿,这是凌晨2点,也许我错过了什么。我是从头开始写的:

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 :(得分:1)

我看到示例代码中的复杂性使它(可能)比它需要的更难。

正则表达式非常棒。如果您想修改此项,我建议您使用此工具: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"
相关问题