我需要用php比较这两个关键字字符串。
$original_keywords = cat, dog, mouse
$possible_keywords_1 = "cat, dog, hamster";
$possible_keywords_2 = "cat, sheep, goat";
我需要一个php脚本将数值“1”分配给第一个可能的字符串(1个匹配),将“2”分配给第二个(2个匹配)。谁能帮助我?
答案 0 :(得分:2)
$original_keywords = array("cat", "dog", "mouse");
$possible_keywords1 = preg_split('/,\s*/', "cat, dog, hamster");
echo count(array_intersect($original_keywords, $possible_keywords1))
答案 1 :(得分: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));
答案 2 :(得分: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));