Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 378
  • Last Modified:

couting number of $occurrences

Hi, I'm trying to count number of $occurrences for a whole word in a text. I tried to use  substr_count(strtolower($text),strtolower($word));
but its appear to not working properly is there anyway to use it for a whole word match only ? or I have to use preg
0
Nura111
Asked:
Nura111
  • 3
  • 2
1 Solution
 
käµfm³d 👽Commented:
I believe you would want preg, but I could be mistaken. Here is a preg example:
preg_match_all("/\b$word\b", $text, $matches);
echo count($matches);

Open in new window

0
 
käµfm³d 👽Commented:
I missed the case-insensitivity part of your example. You can easily add that with the "i" modifier. (I also forgot to include my closing delimiter--added below).
preg_match_all("/\b$word\b/i", $text, $matches);
echo count($matches);

Open in new window

0
 
Nura111Author Commented:
the count part is not working it always return 1
0
 
Nura111Author Commented:
so im adding PREG_PATTERN_ORDER and count($matches[0])
0
 
käµfm³d 👽Commented:
Ah. I always forget how arrays work in PHP. You are correct, it should be:
echo count($matches[0]);

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now