假设你有:
$text1="我可以等一整夜";
$text2="我们可以唱一整天";
我需要一个函数来告诉我在两个语句中发现相同的 3 个单词,即can
, for
, all
。
谢谢
您可以使用explode来获取单词数组:
$text1="i can wait for all night";
$text2="we can sing for all day";
$text1arr = explode(" ", $text1);
$text2arr = explode(" ", $text2);
然后,您可以使用array_intersect来获取常用词:
$result = array_intersect($text1arr , $text2arr);
最后,您可以使用 count 来获取常用词的数量:
$num_in_common = [count][3]($result);
$words1 = str_word_count($text1, 2);
$words2 = str_word_count($text2, 2);
$common_words = $result = array_intersect($words1, $words2);
$common_count = sizeof($common_words);
提醒一下,SO 不是编码服务,当简单地询问答案时,人们不会高兴,而提问者似乎没有付出任何努力。但是,这里有一点可以帮助您入门。
当给定两个或多个数组时,该array_intersect
函数会为您提供一个包含输入之间共享的所有值的数组。
至于查找值的位置,该array_search
函数为数组中的值提供一个键。
如果所有数组为输出数组中的某个值共享相同的键array_intersect
,那么您知道该值由所有数组共享,并且位于相同的位置。
如何实现这一切取决于你。