php find array value in string

ii silver ii

ǝɹıɟpǝʞɔı&
Dec 18, 2008
767
23
0
If you have a php string and want to count the number of occurrences of array values within that string how would you go about doing that?

I'm trying to find an answer but the only thing I can find is string in arrays which is the other way around and substr_count but you can only use a string as the needle not an array of values to look for?
 


Do you mean something like:
PHP:
$string = 'If you have a php string and want to count the number of occurrences of  array values within that string how would you go about doing that?';
$search = array('php', 'string');
if so:

PHP:
$counts=array();
$count_all=0;

foreach($search as $needle)
{
$counts[$needle] = substr_count($string, $needle);
$count_all += substr_count($string, $needle);
}
$count_all will give you the total occurrences of all words: 3
$counts will give you the total occurrences of each word:

PHP:
array(
'php' => 1,
'string'=>2
);
 
  • Like
Reactions: ii silver ii