2014-06-13 69 views
-3

在其他字符串中是否有PHP函數(或oneliner)用於查找其中一個字符串(存儲在數組中)?PHP在haystack(字符串)中找到neeedles(字符串數組)之一

# find one of those strings 
$needles = [ 
'aaa', 
'bbb', 
]; 

# anywhere in this string 
$haystack = 'ccccccaaa'; 

# returns TRUE when $haystack contains any of strings in $needles 
is_there($needles , $haystack) === true 
+3

花了不到10二,我沒有-1解釋? – Martin

+0

可能重複:http://stackoverflow.com/questions/9890919/in-php-is-there-a-function-like-stristr-but-for-arrays –

+0

可能的重複[在strpos中使用數組作爲針頭] (http://stackoverflow.com/questions/6284553/using-an-array-as-needles-in-strpos) – Steve

回答

1

使用preg_match()

function is_there($needles, $haystack) { 
    $p = sprintf('/%s/', implode('|', $needles)); 
    return (bool) preg_match($p, $haystack); 
} 

用法:

var_dump(is_there($needles , 'ccccccaaa')); 
var_dump(is_there($needles , 'foobar')); 

輸出:

bool(true) 
bool(false) 
相關問題