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

FilmJ picture FilmJ · Jul 16, 2009 · Viewed 12.4k times · Source

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.

Answer

Ian Elliott picture Ian Elliott · Jul 16, 2009

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