This version will work no matter what kind of "space" you use between words and can be easily extended to handle other characters... it currently supports any white space character plus , . ; ? !
function getSnippet( $str, $wordCount = 10 ) {
return implode(
'',
array_slice(
preg_split(
'/([\s,\.;\?\!]+)/',
$str,
$wordCount*2+1,
PREG_SPLIT_DELIM_CAPTURE
),
0,
$wordCount*2-1
)
);
}
For those who should might prefer the original formatting :)
function getSnippet( $str, $wordCount = 10 ) {
return implode( '', array_slice( preg_split('/([\s,\.;\?\!]+)/', $str, $wordCount*2+1, PREG_SPLIT_DELIM_CAPTURE), 0, $wordCount*2-1 ) );
}