首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从PHP中包含完整句子的文本中获取特定的单词?

如何从PHP中包含完整句子的文本中获取特定的单词?
EN

Stack Overflow用户
提问于 2019-01-03 06:32:57
回答 2查看 452关注 0票数 1

我想从一篇文章中得到一些句子。

示例文本如下,

鹰头狮低声打断了声音。“一点也不,”渡渡鸟指着树林里的嘈杂声说。(她把他想给你听了,Though.Gryphon低声打断了他的话。)“一点也不,”渡渡鸟指着树林里的嘈杂声说。(她把他想给你听了,Though.Gryphon低声打断了他的话。)“一点也不,”渡渡鸟说,指着树林里混乱的喧闹声

到目前为止,我所做的是能够从一个大的文本中得到30个单词,但最后,我有一个不完整的句子,我想删除这样的句子。

这是得到30个单词的函数,

代码语言:javascript
运行
复制
/**
 * @param $sentence
 * @param int $count
 * @return mixed
 */
function get_words($sentence, $count = 30) {
    preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
    return $matches[0];
}

我在下面的问题中使用了上述函数

How to select first 10 words of a sentence?

当我把上面的文字传递给函数时,我得到了这样的输出,

鹰头狮低声打断了声音。“一点也不,”渡渡鸟指着树林里混乱的吵闹声说。(她把他当成你了,Though.Gryphon打断了他的话)。

在这里,最后一句是不完整的,我不希望在我的输出这样。

有办法做到这一点吗?

我正在与PHP和Laravel合作,任何类型的帮助和建议都很感谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-01-03 07:24:29

下面的代码可能对您有帮助。

代码语言:javascript
运行
复制
<?php
$sen="Gryphon interrupted in a low voice. 'Not at all,' said the Dodo, pointing to the confused clamour of the wood--(she considered him to you, Though.Gryphon interrupted in a low voice. 'Not at all,' said the Dodo, pointing to the confused clamour of the wood--(she considered him to you, Though.Gryphon interrupted in a low voice. 'Not at all,' said the Dodo, pointing to the confused clamour of the wood--(she considered him to you, Though.";
$cropped_data =  get_words($sen);
$strlength = strlen ( $cropped_data );
$remains=  complete_sentence(substr($sen,$strlength));

function complete_sentence($content) {
    $pos = strpos($content, '.');
    return substr($content, 0, $pos+1);
}

function get_words($sentence, $count = 30) {
    preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
    return $matches[0];
}

echo "complete sentence<br/>".$cropped_data.$remains;
?>

谢谢。

票数 1
EN

Stack Overflow用户

发布于 2019-01-03 07:40:20

代码语言:javascript
运行
复制
function get_words($sentence, $count = 30) {

  preg_match("/(?:w+(?:W+|$)){0,$count}/", $sentence, $matches);

  return $matches[0];
};

$sentence = "Gryphon interrupted in a low voice. 'Not at all,' said the Dodo, pointing to the confused clamour of the wood--(she considered him to you, Though.Gryphon interrupted in a low voice. 'Not at all,' said the Dodo, pointing to the confused clamour of the wood--(she considered him to you, Though.Gryphon interrupted in a low voice. 'Not at all,' said the Dodo, pointing to the confused clamour of the wood--(she considered him to you, Though.";

$cropSentence =  get_words($sentence);

$finalSentence= substr($cropSentence, 0, strrpos($cropSentence, "."));
echo $finalSentence;

它将返回到(.)的最后一次出现;

鹰头狮低声打断了声音。“一点也不,”渡渡鸟说,指着树林里混乱的喧闹声

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54017380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档