我正在尝试使用PHP执行以下操作:
$user_agent = "Mozilla/5.0 (Linux; Android 4.4.2; SAMSUNG-GT-I9505 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36"
if (preg_match('/android/i', $user_agent)) {
$version = preg_split('Android (.*?);', $user_agent); //regex should be `Android (.*?);` which would give me 4.4.2
}
但我真的不知道如何正确使用代码,$ version之后的部分是猜测。有人可以帮帮我吗?也许用preg_split?我希望4.4.2存储在$ version中。
答案 0 :(得分:2)
这就是你需要的:
$user_agent = "Mozilla/5.0 (Linux; Android 4.4.2; SAMSUNG-GT-I9505 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36";
preg_match('/Android ([\d\.]+)/im', $user_agent, $matches);
$version = $matches[1];
echo $version;
//4.4.2
<强>说明强>:
Android ([\d\.]+)
-----------------
Match the character string “Android ” literally (case insensitive) «Android »
Match the regex below and capture its match into backreference number 1 «([\d\.]+)»
Match a single character present in the list below «[\d\.]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
A “digit” (any decimal number in any Unicode script) «\d»
The literal character “.” «\.»