Search code examples
phpexplodepreg-split

Get first 2 sentences in php


We have this code that grabs the first two sentences of a paragraph and it works perfect except for the fact that it only counts periods. It needs to get the first two sentences even if they have exclamation points or question marks. This is what we are currently using:

function createCustomDescription($string) {
  $strArray = explode('.',$string);
  $custom_desc = $strArray[0].'.';
  $custom_desc .= $strArray[1].'.';

  return htmlspecialchars($custom_desc);
}

Any ideas how to also check for question marks and/or exclamation points?


Solution

  • You could use preg_split with a regex for the endings that you want with the PREG_SPLIT_DELIM_CAPTURE option, this will maintain the punctuation used.

    function createCustomDescription($string) {
        $split = preg_split('/(\.|\!|\?)/', $string, 3, PREG_SPLIT_DELIM_CAPTURE);
        $custom_desc = implode('', array_slice($split, 0, 4));
    
        return htmlspecialchars($custom_desc);
    }