2

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?

alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46
dems59
  • 25
  • 6
  • 1
    Possible duplicate of [Php multiple delimiters in explode](http://stackoverflow.com/questions/4955433/php-multiple-delimiters-in-explode) – Asur Mar 09 '16 at 15:45

4 Answers4

3

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);
}
MajicBob
  • 487
  • 2
  • 8
2
function createCustomDescription($string) 
{

  $strArray  = preg_split('/(\.|\!|\?)/', $string, 3, PREG_SPLIT_DELIM_CAPTURE);      
  $strArray  = array_slice($strArray, 0, 4);

  return htmlspecialchars(implode('', $strArray));

}
Springie
  • 718
  • 5
  • 8
1

Try to use this code:

function createCustomDescription($string) {
    $strArray = preg_split( '/(\.|!|\?)/', $string);
    $custom_desc = $strArray[0].'.';
    $custom_desc .= $strArray[1].'.';

    return htmlspecialchars($custom_desc);
}
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46
  • 1
    This is a good solution for locating the end of the first 2 paragraphs and replacing the punctuation with a period, but, we really wanted to keep the existing punctuation which is what @MajicBob came up with. I realize I didn't mention that in the original post, but thank you for helping! – dems59 Mar 09 '16 at 16:37
1

First replace all ? and ! with a full stop (.) . Then use your usual code Using

str_replace("?",".",$paragraph);
str_replace("!",".",$paragraph);

Then use your code to explode with a (.)

Sarthak Mishra
  • 1,033
  • 1
  • 11
  • 27