match string with array values

Hi Experts,
i have a string and an array with categories and targetnumbers.
Now i want to find out, how many times a category match with the given string.

Sorry it´s a german sentence. The Important words are "DJ" and "house".

Now the result with the code below is:
array(2) { [0]=> int(2) [1]=> int(4) }
And the result should be:
array(2) { [4]=> int(3) [2]=> int(1) }

The array key represent the "target" value from the array. The value of target should be the match count. The count for "DJ" or "DJs" is 3 and the count of "house" is 1.

$outputArray = array();
$string = "...GEORGE MOREL aus den USA wird eingeflogen und euch zu verstehen DJ geben warum er eine lebende House Legende ist. 
DJs und Produzenten aus aller Welt erweisen dem meistgebuchten US DJ der Welt Ihren Respekt.";
$matches = array();
$matches[] = array("category" => "sports", "target" => 1);
$matches[] = array("category" => "soccer", "target" => 1);
$matches[] = array("category" => "baseball", "target" => 1);
$matches[] = array("category" => "party", "target" => 2);
$matches[] = array("category" => "disco", "target" => 2);
$matches[] = array("category" => "house", "target" => 2);
$matches[] = array("category" => "concert", "target" => 3);
$matches[] = array("category" => "openair", "target" => 3);
$matches[] = array("category" => "DJ", "target" => 4);
$res = array();
foreach ($matches as $val)
	if (preg_match("/".$val["category"]."/i",$string))
		$res[] = $val["target"];

Open in new window

Who is Participating?
RoonaanConnect With a Mentor Commented:
Hello bibabutze,

Instead of preg_match, you could use preg_match_all:
if(preg_match_all('/'.preg_quote($val['category'],'/').'/i', $string, $m)) {
  $count = count($m[0]);
  if(isset($res[$val['target']])) {
    $res[$val['target']]+= $count;
  } else {
    $res[$val['target']] = $count;


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.