PHP 从字符串中获取最后n个句子

PHP Get last n sentences from a string

假设我有下面的字符串

$string = 'PHP Coding.
Hello World!
Merry Christmas!
Happy New Year!
Merry Super Early Next Christmas?
I want Pizza, and Cake
Hehehe
Hohohoho';

如何从字符串中获取最后 n 个句子,例如最后 3 个句子,输出结果如下:

I want Pizza, and Cake
Hehehe
Hohohoho

编辑:我正在使用来自 sql 的数据

这应该适合你:

<?php

    $string = 'PHP Coding.
            Hello World!
            Merry Christmas!
            Happy New Year!
            Merry Super Early Next Christmas?
            I want Pizza, and Cake
            Hehehe
            Hohohoho';

    list($sentence[], $sentence[], $sentence[]) = array_slice(explode(PHP_EOL, $string), -3, 3);

    print_r($sentence);

?>

输出:

Array ( [2] => Hohohoho [1] => Hehehe [0] => I want Pizza, and Cake )

编辑:

这里你可以定义你想要的后面几句:

<?php

    $string = 'PHP Coding.
            Hello World!
            Merry Christmas!
            Happy New Year!
            Merry Super Early Next Christmas?
            I want Pizza, and Cake
            Hehehe
            Hohohoho';

    $n = 3;

    $sentence = array_slice(explode(PHP_EOL, $string), -($n), $n);
    $sentence = array_slice(explode(PHP_EOL, nl2br($string)), -($n), $n); // Use this for echoing out in HTML
    print_r($sentence);

?>

输出:

Array ( [0] => I want Pizza, and Cake [1] => Hehehe [2] => Hohohoho )
$string = 'PHP Coding.
Hello World!
Merry Christmas!
Happy New Year!
Merry Super Early Next Christmas?
I want Pizza, and Cake
Hehehe
Hohohoho';



function getLast($string, $n){
    $splits = explode(PHP_EOL, $string);
    return array_slice($splits, -$n, count($splits));
}

$result = getLast($string, 2);
var_dump($result);