• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 401
  • Last Modified:

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"];
	}
}
 
 
var_dump($res);
exit;

Open in new window

0
bibabutze
Asked:
bibabutze
1 Solution
 
RoonaanCommented:
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;
  }
}

Regards,

Roonaan
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

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