目前我这样做是为了获得前20个单词:
$thewhat = $row['about_field'];
$shortened = implode(' ', array_slice(explode(' ', $thewhat), 0, 20));
但它看起来很乱,我怎么能这样才能只选择前2个句子?
答案 0 :(得分: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];
正则表达式从What is a regular expression for parsing out individual sentences?被盗,但稍有改动,不包括每个句子后的匹配空格。
答案 1 :(得分: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;
?>