如何从php用户代理提取移动设备名称?

问题描述 投票:1回答:2

我正在编写代码来保存用户的设备详细信息。但是当我使用PHP用户代理时,它返回整个信息串。如何仅提取设备名称,仅适用于iPhone 6,Samsung Galaxy a5等型号名称?

我尝试了一些正则表达式,但这将是长代码,我不能涵盖每一个设备。

我正进入(状态

Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1

我只想要iPhone OS 10_3_1

php user-agent
2个回答
1
投票

在这里你的代码。

$str = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1";

$pos1 = strpos($str, '(')+1;
$pos2 = strpos($str, ')')-$pos1;
$part = substr($str, $pos1, $pos2);
$parts = explode(" ", $part);
echo $parts[2].' '.$parts[3].' '.$parts[4];

1
投票

用户代理有很多种不同的编写方式,很难通过正则表达式或简单的逻辑来提取信息。更好的方法是搜索您知道可能发生的给定设备的列表,例如来自this answer,但这可能使得很难提取版本信息。

相反,我建议使用第三方库,如device-detector,并使用以下内容:

use DeviceDetector\DeviceDetector;

// Fetch the user agent
$userAgent = $_SERVER['HTTP_USER_AGENT'];

// Create an instance of DeviceDetector
$dd = new DeviceDetector($userAgent);

// Extract any information you want
$osInfo = $dd->getOs();
$device = $dd->getDeviceName();
$brand = $dd->getBrandName();
$model = $dd->getModel();
© www.soinside.com 2019 - 2024. All rights reserved.