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

时间:2015-01-07 14:27:00

标签: php mysql paragraphs

我们说我有下面的字符串

$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中的数据

2 个答案:

答案 0 :(得分:3)

这应该适合你:

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

答案 1 :(得分:0)

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