0

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?

4

2 回答 2

1

如果您的句子用点分隔,您可以尝试

$shortened = implode('.', array_slice(explode('.', $thewhat), 0, 2)) . '.';

因为这仅适用于用点分隔的句子和句子中没有点的句子,所以这里有一个正则表达式,可以帮助您处理大部分内容:

$pattern = '/(\S.+?[.!?])(?:\s+|$)/';
$matches = preg_split($pattern, $text, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
$shortened = $matches[0] .' '. $matches[1];

正则表达式是从:什么是解析单个句子的正则表达式?但稍作修改,不包括每个句子后匹配的空格。

于 2011-11-07T21:40:59.257 回答
1
<?
//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;
?>
于 2011-11-07T21:52:45.297 回答