Search code examples
phpmysqlparagraphs

PHP Get last n sentences from a string


Let's say I have the string below

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

How do I get the last n sentences from the string, for example, the last 3 sentences, which should give the following output:

I want Pizza, and Cake
Hehehe
Hohohoho

Edit: I'm using data from sql


Solution

  • This should work for you:

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

    Output:

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

    EDIT :

    Here you can define how many sentence you want from the back:

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

    Output:

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