Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does anyone have a PHP snippet of code for grabbing the first "sentence" in a string?

If I have a description like:

"We prefer questions that can be answered, not just discussed. Provide details. Write clearly and simply."

And all I want is:

"We prefer questions that can be answered, not just discussed."

I figure I would search for a regular expression, like "[.!\?]", determine the strpos and then do a substr from the main string, but I imagine it's a common thing to do, so hoping someone has a snippet lying around.

like image 476
FilmJ Avatar asked Jul 16 '09 05:07

FilmJ


People also ask

How can I get first sentence in PHP?

Using a combination of the PHP functions strpos() and substr() we can extract the first sentence from the above text like so by looking for the location of the first period / full stop in the content and returning everything up to and including it. Then doing this: echo first_sentence($content);

How do I get the first index of a string in PHP?

The strpos() function finds the position of the first occurrence of a string inside another string. Note: The strpos() function is case-sensitive.


2 Answers

A slightly more costly expression, however will be more adaptable if you wish to select multiple types of punctuation as sentence terminators.

$sentence = preg_replace('/([^?!.]*.).*/', '\\1', $string);

Find termination characters followed by a space

$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $string);
like image 185
Ian Elliott Avatar answered Oct 29 '22 13:10

Ian Elliott


My previous regex seemed to work in the tester but not in actual PHP. I have edited this answer to provide full, working PHP code, and an improved regex.

$string = 'A simple test!';
var_dump(get_first_sentence($string));

$string = 'A simple test without a character to end the sentence';
var_dump(get_first_sentence($string));

$string = '... But what about me?';
var_dump(get_first_sentence($string));

$string = 'We at StackOverflow.com prefer prices below US$ 7.50. Really, we do.';
var_dump(get_first_sentence($string));

$string = 'This will probably break after this pause .... or won\'t it?';
var_dump(get_first_sentence($string));

function get_first_sentence($string) {
    $array = preg_split('/(^.*\w+.*[\.\?!][\s])/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
    // You might want to count() but I chose not to, just add   
    return trim($array[0] . $array[1]);
}
like image 25
dyve Avatar answered Oct 29 '22 12:10

dyve