0

Assuming I have an array of colors:

$colors = array('black','yellow','red');
$color = 'reddish';

How can I calculate the number of occurrence of them? Because substr_count() may be well detecting 'red', but 'reddish' won't be included. So I need to match the string precisely despite what's before or after it.

$string = implode(' ', $colors);
echo substr_count($string, $color);
8
  • 2
    Do you want reddish to be a match or not? I don't understand. Commented Jul 20, 2014 at 19:15
  • Yes, indeed. I want it to be counted. As well as any word/string that has the 'red' substring within. i.e. 9@)redV_%1bm. Anything Commented Jul 20, 2014 at 19:17
  • That´s what substr_count does... Commented Jul 20, 2014 at 19:17
  • Yes but can you run the above code and see if you get 'reddish' counted? Commented Jul 20, 2014 at 19:18
  • I don't need to run it. I know what it does. I don't understand why you expect it to work what you have. You are searching for black yellow red in the string reddish hence it is not a match Commented Jul 20, 2014 at 19:21

1 Answer 1

1

How about something like this?

$colors = array('black', 'yellow', 'red');
$color = 'reddish';

$string = implode('|', $colors);

preg_match_all("/".$string."/i", $color, $matches);

print_r($matches); // will print an array of the matches
echo count($matches[0]); // will echo how many matches were made

This will output 1, and if $color were to equal "reddish yellowy" the output would be 2 since it matches both "red" and "yellow" from the $colors array.

Sign up to request clarification or add additional context in comments.

1 Comment

Solves the issue. Thank you for your time :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.