IMO可以在这里使用正则表达式:
$pattern = '/' . implode('|', array_map('preg_quote', $needle)) . '/i';
foreach($file_list as $file) {
if(preg_match($pattern, $file)) {
// do something
}
}
这是一种更“创造性”的方法(但它使用内部循环并且很可能更慢,因为您实际上在数组上循环了几次):
function cstrstr($haystack, $needle) {
return strstr($haystack, $needle) !== false;
}
foreach($file_list as $file) {
if(array_sum(array_map('cstrstr',
array_pad(array($file), count($needle), $file),
$needle))) {
// do something
}
}
但正则表达式的优点应该是显而易见的:你必须只创建一次模式,而在“有趣”的解决方案中,你总是需要为每个$文件创建一个长度计数数组($needle).