从数据库中查找一个包含单词的句子



我想用一个例子来解释我试图实现的目标。假设我的posts表中有两行。

It snows a lot in winter in Norway. While it barely snows where I live.
I run four miles every morning. I am trying to get fit.

当我搜索in winter时,我想得到句子It snows a lot in winter in Norway.

我知道我可以和吵架

$posts = AppModelsPost::where('body', 'like', "%{in winter}%")->get();

但是我不知道如何得到确切的句子。

虽然从技术上讲,使用SQL获取准确的句子是可能的,但最好使用PHP从集合中获取准确的语句。

我已经创建了一个使用集合的示例(因为您使用的是Laravel(,从您提供的Post查询开始(尽管我确实从类似的字符串中删除了大括号(。

1.使用类正文搜索查询获取帖子集合

$posts = Post::where('body', 'like', "%in winter%")->get();

2.将帖子集合映射到单个句子。压扁以删除空句子

$postSentences = $posts->map( function($post) {
// preg split makes sure the text is splitted on . or ! or ?
return preg_split('/.|?|!/', $post->body); 
})->flatten();

3.使用过滤器和Str::contains((获取相应的句子

$matchingSentences = $postSentences->filter( function($sentence) {
return Str::contains($sentence, 'in winter');
});

$matchingSentences应返回:

IlluminateSupportCollection 
all: [
"It snows a lot in winter in Norway",
],
}

该示例可能会根据您的需要进行更改/缩短。但这应该能解决上述问题。

相关内容

最新更新