使用php从字符串中获取第一个句子


Get the first sentence from string using php

我有一些内容存储在一个变量中,它看起来像"

$content = "This is a test content and the content of the url is http://www.test.com. The is a second sentence.";
现在我的代码是
$pos = strpos($content, '.');
$firstsentence = substr($content, 0, $pos);

上面的代码不起作用,因为字符串已经包含了一个带点的url。

考虑到字符串包含超链接的事实,我如何得到第一个句子?

请分享其他文本场景。这在您的示例中工作得很好:

$sentences = 'This is a test content and the content of the url is http://www.test.com. The is a second sentence.';
preg_match('/(http|https):(.*?)com/', $sentences, $match);
$sentences = preg_replace('/(http|https):(.*?)com/', '', $sentences);
$pos = strpos($sentences, '.');
$pos .= -1;
$firstsentence = substr($sentences, 0, $pos) .$match[0].'.';
//This is a test content and the content of the url is http://www.test.com.

一般来说,我认为您还必须寻找<sentence-end-punct>"<whitespace>, "<sentence-end-punct><whitespace><sentence-end-punct><whitespace>(其中包括行尾)。这是一篇非常普通的英语文章,不是你特别能控制的,还是语法非常有限?对于非英语文本,可以有额外的规则,例如在标点符号和引号之间放置空格。

你在这里想要完成什么?你真的需要把文本拆分成单独的句子吗,或者你只是想创造一个"挑逗"。对于后一种情况,只需在某些字符之前的完整单词处截断文本,并添加省略号(…)。