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