如何找出在有/没有雄辩的结果/字符串中使用了多少单词



我想知道一个单词在laravel中的使用量。我不确定雄辩是否可能,所以如果不可能,我如何用php做到这一点?

示例:

我从下面的查询中得到结果:

$posts = Posts::where('post_body', 'like', '%'.$name.'%')->get();
$result = [];
foreach ($posts as $post) {
// Logic here to push to result and how much searched word used in result and push to array
}
return $result;

所以如果我搜索文件名12345.jpeg,我想知道12345.jpegpost_body中使用了多少。检查多少,然后将使用计数和结果推送到数组。

更多示例:

张贴正文结果:";这是12345.jpeg和CCD_=>返回字符串中12345.jpeg的2次使用

张贴正文结果:";这是12345.jpeg和CCD_ 5=>返回字符串中12345.jpeg的3次使用

贴体结果:happy world, happy life, Happy post=>返回结果中使用了多少happy。这是我对CCD_ 8感到满意以来的2次。

您可以使用PHP的substr_count函数。

例如:

$s = "happy world, happy life, Happy post";
echo substr_count($s, "happy"); //yields 2.

来自文档:substra_count((返回针子字符串出现的次数在干草堆里。请注意,针区分大小写。

参考文档链接:https://www.php.net/manual/en/function.substr-count.php

以下是您需要的。

$posts = Posts::where('post_body', 'like', '%'.$name.'%')->get();
$posts->transform(function ($post) use ($name) {
$post = (object) $post;
$post->occurennces = substr_count($post->post_body, $name);
return $post;
});
return $posts;

最新更新