続きはWEBで。

技術的なこともそうでないことも、自由気ままに書き留めていくためのサイト

UserAgentで条件分岐・種別を取得

UserAgentを「スマートフォン」「タブレット」「PC」のどれかに分類したいときに使う関数+正規表現

function get_device_type(){
    $user_agent = mb_strtolower($_SERVER['HTTP_USER_AGENT']);

    // スマートフォン
    if(preg_match('#\b(ip(hone|od);|android.*mobile)|windows.*phone|blackberry.*|psp|3ds|vita#', $user_agent)){
        $device_type = 'smartphone';
    // タブレット
    }elseif(preg_match('#\ipad|android|kindle|silk|playbook|rim\stablet#', $user_agent)){
        $device_type = 'tablet';
    // PC
    }else{
        $device_type = 'pc';
    }

    return $device_type;
}

ポイントはここ。最初にUserAgentを全て小文字にしてしまうところ。

$user_agent = mb_strtolower($_SERVER['HTTP_USER_AGENT']);

さらにこんな関数を作っておくと個人的には便利かと思ったり。

// スマートフォンか否か判別
function is_smartphone(){
    return get_device_type() === 'smartphone' ? true : false;
}

// タブレットか否か判別
function is_tablet(){
    return get_device_type() === 'tablet' ? true : false;
}

// PCか否か判別
function is_pc(){
    return get_device_type() === 'pc' ? true : false;
}