We help IT Professionals succeed at work.

match string with array values

bibabutze asked
Medium Priority
Last Modified: 2012-05-06
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

Watch Question

Top Expert 2006
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;



Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.