2017-04-04 154 views
0

我正在尋找一種與in_array相同的替代函數,但它也可以檢查搜索項是否僅包含給定元素的一部分而不是整個元素:PHP如何檢查數組是否包含另一個數組的模式

目前與下面的腳本工作:

$attributes = array('dogs', 'cats', 'fish'); 

    if (in_array($attributes, array('dog','cats','fishess'), true)) { 

    * does something for cats, but not for dogs and fish 
     because the function only checks if the given term is identical to the word in the array instead of only a part of the word * 
} 

我將如何建立我起來的功能,使其通過的話只包含在陣列藏漢文字的部分?

首選的例子是這個樣子:

$words = array('fish', 'sharks'); 

if (*word or sentence part is* in_array($words, array('fishing', 'sharkskin')){ 

return 'your result matched 2 elements in the array $words 

} 
+0

http://php.net/manual/en/function.array-intersect.php – mkaatman

+1

更妙的是HTTP:// PHP。 net/manual/en/function.array-uintersect.php – dan08

+0

這類問題的一個重要細節是針陣列的大小和乾草堆陣列的大小是多少。根據這些尺寸,如果性能很重要,答案可能完全不同。 –

回答

0

你可以使用:

array_filter($arr, function($v, $k) { 
    // do whatever condition you want 
    return in_array($v, $somearray); 
}, ARRAY_FILTER_USE_BOTH); 

數組中的每一項調用這個函數$arr一個功能,您可以自定義,你的情況檢查你是否在另一個陣列元素

0

爲什麼不只是使自己的一段代碼/功能?

foreach ($item in $attributes) { 
    foreach ($item2 in array('dog','cats','fishess')) { 
     // Check your custom functionality. 
     // Do something if needed. 
    } 
} 

你可以看看array_intersect,但它不會檢查模式匹配(你莫名其妙地提到?)

array_intersect()返回一個包含了array1的所有值的數組這是存在於所有論據中的。請注意,鍵被保留。

foreach (array_intersects($attributes, array('dog','cats','fishess') { 
    // do something. 
} 
1

將溶液使用array_filterpreg_grep功能:

$words = ['fish', 'sharks', 'cats', 'dogs']; 
$others = ['fishing', 'sharkskin']; 

$matched_words = array_filter($words, function($w) use($others){ 
    return preg_grep("/" . $w . "/", $others); 
}); 

print_r($matched_words); 

輸出:

Array 
(
    [0] => fish 
    [1] => sharks 
) 
1

嘗試下面的代碼:

<?php 
$what = ['fish', 'sharks']; 
$where = ['fishing', 'sharkskin']; 

foreach($what as $one) 
    foreach($where as $other) 
     echo (strpos($other, $one)!==false ? "YEP! ".$one." is in ".$other."<br>" : $one." isn't in ".$other."<br>"); 
?> 

希望它可以幫助=}

+0

這是沒有技巧的基本方法(因爲循環是明確的,並且因爲您使用了足夠執行此任務的「strpos」)。然而,不要顯示狗屎(並假設用戶需要html),最好返回一個已過濾的數組。 –

+0

您好@CasimiretHippolyte,我相信他會更好地使用結果,我已經顯示了一些狗屎,因爲他可以運行此代碼(無需修改它)並查看它是否適合他的問題...有時簡單性更聰明.. 。 – rafsb

0

我會去:

$patterns = array('/.*fish.*/', '/.*sharks.*/'); 
$subjects = array('fishing', 'aaaaa', 'sharkskin'); 
$matches = array(); 
preg_replace_callback(
    $patterns, 
    function ($m) { 
     global $matches; 
     $matches[] = $m[0]; 
     return $m[0]; 
    }, 
    $subjects 
); 

print_r($matches); // Array ([0] => fishing [1] => sharkskin) 
+0

沒有什麼可以替代的,不要使用'preg_replace ...',不管用什麼原因都不要使用'global'。 –

+0

@CasimiretHippolyte爲什麼不使用全球?這是一種語言功能;)很顯然,preg取代回調函數,它被用於不同的原因。 – bluehipy

相關問題