Atlas-Pio
Atlas-Pio

Reputation: 1153

How to find out how much word used in a result/string with/without eloquent?

I want to find out how much a word used in laravel with eloquent. I'm not sure if it's possible with eloquent so if it's not how can i do this with php?

Example :

I'm getting results from below query :

    $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;

so if i searched something like file name 12345.jpeg, i want to know how much 12345.jpeg used in post_body. check how much then push usage count with result to array.

More Example :

post body result : "this is 12345.jpeg and <img src="12345.jpeg"/>" => Return 2 time usage of 12345.jpeg in string

post body result : "this is 12345.jpeg and <img src="12345.jpeg"/> and more 12345.jpeg" => Return 3 time usage of 12345.jpeg in string

post body result : happy world, happy life, Happy post => Return how much happy is used in the result. which is 2 times since I've got 1 happy with H.

Upvotes: 0

Views: 56

Answers (2)

OneSimpleGeek
OneSimpleGeek

Reputation: 148

Here is what you need.

$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;

Upvotes: 1

user3532758
user3532758

Reputation: 2271

You can use PHP's substr_count function.

Eg:

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

From documentation: substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.

Documentation link for reference: https://www.php.net/manual/en/function.substr-count.php

Upvotes: 2

Related Questions