-2

以下の文字列があるとしましょう

$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のデータを使用しています

4

2 に答える 2

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 )
于 2015-01-07T14:29:40.987 に答える
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);
于 2015-01-07T14:34:57.963 に答える