2011-07-12 154 views
1

我需要比較這兩個字符串的字符串與PHP。PHP比較關鍵字字符串

$original_keywords = cat, dog, mouse 

$possible_keywords_1 = "cat, dog, hamster";  
$possible_keywords_2 = "cat, sheep, goat"; 

我需要的PHP腳本的「1」的數值分配給所述第一可能的字符串(1個匹配)和「2」到第二(2個匹配)。任何人都可以幫我嗎?

回答

2
$original_keywords = array("cat", "dog", "mouse"); 
$possible_keywords1 = preg_split('/,\s*/', "cat, dog, hamster"); 
echo count(array_intersect($original_keywords, $possible_keywords1)) 
1
$original_keywords = "cat, dog, mouse"; 
$possible_keywords_1 = "cat, dog, hamster"; 
$possible_keywords_2 = "cat, sheep, goat"; 

// Put the input keywords into an array 
$keywords = explode(', ', $original_keywords); 

// Put all incoming keywords into one big array (you can add as many arrays 
// as you want here) 
$input = array_merge(
    explode(', ', $possible_keywords_1), 
    explode(', ', $possible_keywords_2)); 

// Count how many times each keywords from $input appears 
$count = array_count_values($input); 

// Filter out from $count any keyword that is not present in $keywords 
$result = array_intersect_key($count, array_flip($keywords)); 

See it in action

0

你可以做,使用和explode組合array_intersect

以下是代碼入手:

$possible_keywords_1_array = explode(",", $possible_keywords_1); 
$possible_keywords_2_array = explode(",", $possible_keywords_2); 
$matches = count(array_intersect($possible_keywords_1_array, $possible_keywords_2_array));