Reputation: 3168
Currently i am doing this to get the first 20 words:
$thewhat = $row['about_field'];
$shortened = implode(' ', array_slice(explode(' ', $thewhat), 0, 20));
But it looks messy, how can i do it so that only first 2 sentences are selected?
Upvotes: 0
Views: 332
Reputation: 12586
If your sentences are delimited with dots you could try
$shortened = implode('.', array_slice(explode('.', $thewhat), 0, 2)) . '.';
Since this will only work for sentences delimited with dots and sentences without dots in the sentence here's a regex that could help you with most parts:
$pattern = '/(\S.+?[.!?])(?:\s+|$)/';
$matches = preg_split($pattern, $text, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$shortened = $matches[0] .' '. $matches[1];
The regex is stolen from: What is a regular expression for parsing out individual sentences? but is slightly altered to not include the matched whitespaces after each sentence.
Upvotes: 1
Reputation: 11829
<?
//extend this regexp [.?] as you need.
$text = 'codepad is an online compiler/interpreter, and a simple collaboration tool.Paste your code below, and codepad will run it and give you a short URL you can use to share it in chat or email? qwe asd zxc.';
$sentences = preg_split('/([.?]+)/', $text, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
/*
print_R($sentences);
Array
(
[0] => codepad is an online compiler/interpreter, and a simple collaboration tool
[1] => .
[2] => Paste your code below, and codepad will run it and give you a short URL you can use to share it in chat or email
[3] => ?
[4] => qwe asd zxc
[5] => .
)
*/
$shorted = $sentences[0] . $sentences[1] . $sentences[2] . $sentences[3];
echo $shorted;
?>
Upvotes: 1