PHP - get first two sentences of a text?

后端 未结 9 1906
慢半拍i
慢半拍i 2021-02-05 22:52

My variable $content contains my text. I want to create an excerpt from $content and display the first sentence and if the sentence is shorter than 15

9条回答
  •  盖世英雄少女心
    2021-02-05 23:30

    Here's a quick helper method that I wrote to get the first N sentences of a given body of text. It takes periods, question marks, and exclamation points into account and defaults to 2 sentences.

    function tease($body, $sentencesToDisplay = 2) {
        $nakedBody = preg_replace('/\s+/',' ',strip_tags($body));
        $sentences = preg_split('/(\.|\?|\!)(\s)/',$nakedBody);
    
        if (count($sentences) <= $sentencesToDisplay)
            return $nakedBody;
    
        $stopAt = 0;
        foreach ($sentences as $i => $sentence) {
            $stopAt += strlen($sentence);
    
            if ($i >= $sentencesToDisplay - 1)
                break;
        }
    
        $stopAt += ($sentencesToDisplay * 2);
        return trim(substr($nakedBody, 0, $stopAt));
    }
    

提交回复
热议问题