PHP - get first two sentences of a text?

2019-03-16 06:18发布

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 characters, I would like to display the second sentence.

I've already tried stripping first 50 characters from the file, and it works:

<?php echo substr($content, 0, 50); ?>

But I'm not happy with results (I don't want any words to be cut).

Is there a PHP function getting the whole words/sentences, not only substr?

Thanks a lot!

标签: php substring
9条回答
ゆ 、 Hurt°
2楼-- · 2019-03-16 06:33

I figured it out and it was pretty simple though:

<?php
    $content = "My name is Luka. I live on the second floor. I live upstairs from you. Yes I think you've seen me before. ";
    $dot = ".";

    $position = stripos ($content, $dot); //find first dot position

    if($position) { //if there's a dot in our soruce text do
        $offset = $position + 1; //prepare offset
        $position2 = stripos ($content, $dot, $offset); //find second dot using offset
        $first_two = substr($content, 0, $position2); //put two first sentences under $first_two

        echo $first_two . '.'; //add a dot
    }

    else {  //if there are no dots
        //do nothing
    }
?>
查看更多
Lonely孤独者°
3楼-- · 2019-03-16 06:33

There is one for words - wordwrap

Example Code:

<?php

for ($i = 10; $i < 26; $i++) {
    $wrappedtext = wordwrap("Lorem ipsum dolor sit amet", $i, "\n");
    echo substr($wrappedtext, 0, strpos($wrappedtext, "\n")) . "\n";
}

Output:

Lorem
Lorem ipsum
Lorem ipsum
Lorem ipsum
Lorem ipsum
Lorem ipsum
Lorem ipsum
Lorem ipsum dolor
Lorem ipsum dolor
Lorem ipsum dolor
Lorem ipsum dolor
Lorem ipsum dolor sit
Lorem ipsum dolor sit
Lorem ipsum dolor sit
Lorem ipsum dolor sit
Lorem ipsum dolor sit
查看更多
太酷不给撩
4楼-- · 2019-03-16 06:33

Here's a function modified from another I found online; it strips out any HTML, and cleans up some funky MS characters first; it then adds in an optional ellipsis character to the content to show that it's been shortened. It correctly splits at a word, so you won't have seemingly random characters;

/**
 * Function to ellipse-ify text to a specific length
 *
 * @param string $text   The text to be ellipsified
 * @param int    $max    The maximum number of characters (to the word) that should be allowed
 * @param string $append The text to append to $text
 * @return string The shortened text
 * @author Brenley Dueck
 * @link   http://www.brenelz.com/blog/2008/12/14/creating-an-ellipsis-in-php/
 */
function ellipsis($text, $max=100, $append='&hellip;') {
    if (strlen($text) <= $max) return $text;

    $replacements = array(
        '|<br /><br />|' => ' ',
        '|&nbsp;|' => ' ',
        '|&rsquo;|' => '\'',
        '|&lsquo;|' => '\'',
        '|&ldquo;|' => '"',
        '|&rdquo;|' => '"',
    );

    $patterns = array_keys($replacements);
    $replacements = array_values($replacements);


    $text = preg_replace($patterns, $replacements, $text); // convert double newlines to spaces
    $text = strip_tags($text); // remove any html.  we *only* want text
    $out = substr($text, 0, $max);
    if (strpos($text, ' ') === false) return $out.$append;
    return preg_replace('/(\W)&(\W)/', '$1&amp;$2', (preg_replace('/\W+$/', ' ', preg_replace('/\w+$/', '', $out)))) . $append;
}

Input:

<p class="body">The latest grocery news is that the Kroger Co. is testing a new self-checkout technology. My question is: What&rsquo;s in it for me?</p> <p>Kroger said the system, from Fujitsu,

Output:

The latest grocery news is that the Kroger Co. is testing a new self-checkout technology. My question is: What's in it for me? Kroger said the …

查看更多
相关推荐>>
5楼-- · 2019-03-16 06:36

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));
}
查看更多
混吃等死
6楼-- · 2019-03-16 06:36

If I were you, I'd choose to pick only the first sentence.

$t='Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vestibulum justo eu leo.'; //input text
$fp=explode('. ',$t); //first phrase
echo $fp[0].'.'; //note I added the final ponctuation

This would simplyfy things a lot.

查看更多
爷的心禁止访问
7楼-- · 2019-03-16 06:38

For me the following worked:

$sentences = 2;
echo implode('. ', array_slice(explode('.', $string), 0, $sentences)) . '.';
查看更多
登录 后发表回答