$useragent = $_SERVER['HTTP_USER_AGENT'];
$device_array = array("iPhone" , "iPad", "Android");
我想做的是编写一个简单的if语句,查看$device_array
字符串中是否存在任何$useragent
值但不确定如何构造它。
有没有一种理想的方法可以不迭代数组值?
答案 0 :(得分:3)
很简单,使用in_array()
:
if( in_array( $useragent, $device_array)) {
echo $useragent . ' is in the array!';
}
修改:对于通配符匹配,您可以使用正则表达式:
$device_array = array("iPhone" , "iPad", "Android");
$regex = '#' . implode( '|', $device_array) . '#i'; // Note: Escaping the elements in the array with preg_quote() has been omitted
if( preg_match( $regex, $useragent)) {
echo $useragent . ' was matched in the array!';
}