如何使用“Mobile_Detect”类查找客户端操作系统

时间:2013-11-12 13:26:46

标签: php preg-match

我正在使用Mobile_Detect查找客户端使用的OS,我厌倦了这段代码

function get(){

   $user_agent = $this->mobile_detect->getUserAgent();

   foreach($this->mobile_detect->getOperatingSystems() as $os)
   {
        if(preg_match('/('.$os.')/i',$user_agent,$matches))
        {
            $dev = '';
            for($i=0;i<count($matches);$i++){ $dev.=$matches[$i];}
            $registration_os =  $dev;
        }
   }

    print_r($registration_os);


}

$this->mobile_detect->getOperatingSystems()返回数组

 Array
(
    [AndroidOS] => Android
    [BlackBerryOS] => blackberry|\bBB10\b|rim tablet os
    [PalmOS] => PalmOS|avantgo|blazer|elaine|hiptop|palm|plucker|xiino
    [SymbianOS] => Symbian|SymbOS|Series60|Series40|SYB-[0-9]+|\bS60\b
    [WindowsMobileOS] => Windows CE.*(PPC|Smartphone|Mobile|[0-9]{3}x[0-9]{3})|Window Mobile|Windows Phone [0-9.]+|WCE;
    [WindowsPhoneOS] => Windows Phone OS|XBLWP7|ZuneWP7
    [iOS] => \biPhone.*Mobile|\biPod|\biPad
    [MeeGoOS] => MeeGo
    [MaemoOS] => Maemo
    [JavaOS] => J2ME/|Java/|\bMIDP\b|\bCLDC\b
    [webOS] => webOS|hpwOS
    [badaOS] => \bBada\b
    [BREWOS] => BREW
)

但这不起作用,任何想法如何得到这个?

1 个答案:

答案 0 :(得分:1)

我会尝试这样的事情,因为你的正则表达式中没有任何捕获组:

function get(){
    $user_agent = $this->mobile_detect->getUserAgent();

    foreach($this->mobile_detect->getOperatingSystems() as $os => $regex ){
        if( preg_match( '/(' . $regex . ')/i', $user_agent ) ) {
            $registration_os = $os;
            break;
        }
   }

   echo $registration_os;
}