2015-09-13 20 views
8

如何確保字符串和數組之間不存在部分匹配?針對部分字符串的PHP匹配數組

現在我使用的語法:

if (!array_search($operating_system , $exclude)) { 

其中的$值OPERATING_SYSTEM有無關的細節,將來也不會只是機器人,爬行或蜘蛛。

。作爲一個例子$ OPERATING_SYSTEM值

"Mozilla/5.0 (compatible; AhrefsBot/5.0; +http://ahrefs.com/robot/)" 

$排除是不需要的項目組成的數組

$exclude = [ 
    'bot', 
    'crawl', 
    'spider' 
]; 

我想因爲機器人包含這個例子失敗的IF在字符串中都是數組元素。

+4

使用正則表達式而不是一個字符串列表。 – mario

回答

3

此代碼應該很好地爲你工作。

只需使用用戶代理字符串作爲第一個參數和要排除的文本數組作爲第二個參數來調用arraySearch函數。如果陣列中的一個文本在用戶代理串中發現則該函數返回一個1否則返回0。

function arraySearch($operating_system, $exclude){ 
    if (is_array($exclude)){ 
     foreach ($exclude as $badtags){ 
      if (strpos($operating_system,$badtags) > -1){ 
       return 1; 
      } 
     } 
    } 
    return 0; 
} 
3

下面是一個簡單的正則表達式的解決方案:

<?php 
$operating_system = 'Mozilla/5.0 (compatible; AhrefsBot/5.0; +http://ahrefs.com/robot/)'; 
$exclude = array('bot', 'crawl', 'spider'); 

$re_pattern = '#'.implode('|', $exclude).'#'; // create the regex pattern 
if (!preg_match($re_pattern, $operating_system)) 
    echo 'No excludes found in the subject string !)'; 
else echo 'There are some excludes in the subject string :o'; 
?> 
+1

如果您想要_case insensitive_ match,那麼只需在第二個'#':)之後插入一個'i'字符即可:) – someOne