我想在比较2个不同的数组时检查字符串是否包含相同的单词。如果每个数组上都有相同的单词,它将显示每个内部多维数组中的数量
数组1是常见的数组类型,数组2是多维数组
数组1 :
Array
(
[0] => royalty
[1] => free
[2] => picture
)
数组2 :
Array
(
[0] => Array
(
[0] => Affordable and search from millions of royalty free picture
)
[1] => Array
(
[0] => from millions of royalty picture
)
[2] => Array
(
[0] => Provides free picture upload and hosting
)
[3] => Array
(
[0] => Post your picture here Get permanent links
)
[4] => Array
(
[0] => Choose your own unique username to access image
)
)
结果:
Array
(
[0] => Array
(
[0] => 3
)
[1] => Array
(
[0] => 2
)
[2] => Array
(
[0] => 2
)
[3] => Array
(
[0] => 1
)
[4] => Array
(
[0] => 0
)
)
从上面的例子中,数组包含免版税图片的每个单词将显示多维数组中每个单词的数量相同
我正在尝试使用 strcasecmp(),但如果两个字符串包含相同的单词,它只会给我0个结果,我认为它不能为包含这么多单词的字符串提供正确的结果。
答案 0 :(得分:2)
拆分字符串并找到与搜索字词数组的交集
foreach($array2 as &$item)
$item[0] = count(array_intersect($array1, explode(' ', $item[0])));
答案 1 :(得分:1)
最简单的方法可能是循环使用数组2并将每个单词与strstr()或preg_match
的字符串进行比较这样的事情(不完整):
foreach($array2 as $sentence){
foreach($array1 as $word){
if(strstr($word, $sentence) !== false){
$wordsFound++;
}
}
}