0

I trying to solve a bug in my code, i need to get the number of times words appear in a string. It's working fine with single words but i need it to only count the exact sentence (which may contain spaces)

$name = 'apple';
$words = array("apple", "apple juice", "hot apple pie");
$ingredient_count = substr_count($words, $name);

would result in 3, but i only want it to count the exact name, so in this example the result should be 1 because 'apple' on its own only appears 1 time in my array.

$name = 'apple juice';

would also result in 3 but should also be 1

Thank you for any advice

Mystic
  • 147
  • 1
  • 14

1 Answers1

-1

You need to check items which are contained spaces like this:

<?php

$name = 'apple';
$words = array("apple", "apple juice", "hot apple pie");
$count=0;
array_map(function ($item) use($name,&$count){
    if(strpos(trim($item),' ')) $count++;
},$words);

echo 'Count sentences: '.$count;
Tural Rzaxanov
  • 783
  • 1
  • 7
  • 16