繁体   English   中英

使用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> (其中<whitespace>包括行尾)。 这是非常普通的英语文本,不是特别受您控制吗?还是语法非常有限? 对于非英文文本,可以有其他规则,例如在标点和引号之间放置空格。

加:您想在这里完成什么? 您是否真的需要将文本分解成单个句子,还是只是尝试创建“筋急转弯”。 在后一种情况下,只需将一个完整的单词前的文本截断一些字符,然后加上省略号(...)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM