Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - get first two sentences of a text?

Tags:

substring

php

My variable $content contains my text. I want to create an excerpt from $content and display the first sentence and if the sentence is shorter than 15 characters, I would like to display the second sentence.

I've already tried stripping first 50 characters from the file, and it works:

<?php echo substr($content, 0, 50); ?>

But I'm not happy with results (I don't want any words to be cut).

Is there a PHP function getting the whole words/sentences, not only substr?

Thanks a lot!

like image 434
anonymous Avatar asked Jan 14 '11 14:01

anonymous


1 Answers

I figured it out and it was pretty simple though:

<?php
    $content = "My name is Luka. I live on the second floor. I live upstairs from you. Yes I think you've seen me before. ";
    $dot = ".";

    $position = stripos ($content, $dot); //find first dot position

    if($position) { //if there's a dot in our soruce text do
        $offset = $position + 1; //prepare offset
        $position2 = stripos ($content, $dot, $offset); //find second dot using offset
        $first_two = substr($content, 0, $position2); //put two first sentences under $first_two

        echo $first_two . '.'; //add a dot
    }

    else {  //if there are no dots
        //do nothing
    }
?>
like image 177
anonymous Avatar answered Oct 12 '22 11:10

anonymous