Extract first sentence

Either with PHP or a regex. For example, use it to prefill a meta-description field.

Take this regex to take the first sentence from a text, and use the result to prefill a meta description field, when no other meta description data is available. Why? Because it's better to have something relevant (usually, your first sentence is quite relevant for your page, or it hasn't been written well) than nothing. Also, it may help preventing Google to show your navigation menu as a snippet ;)


You can also use this PHP function:

function first_sentence($content) {
    $content = html_entity_decode(strip_tags($content));
    $pos = strpos($content, '.');
    if ($pos === false) {
        return $content;
    } else {
        return substr($content, 0, $pos + 1);

A variant is the following function, that neatly strips a text up to a given number of characters:

function neat_trim($str, $n, $delim='...') {
   $len = strlen($str);
   if ($len > $n) {
       preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
       return rtrim($matches[1]) . $delim;
   else {
       return $str;

What's next?

If you think this was useful to you, it might be for others also. Feel free to share: