2

I am trying to do the following with 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
}

But I do not really know how to get the code right, the part after $version is guesswork. anybody could help me out? Maybe with preg_split? I want 4.4.2 stored in $version.

MOTIVECODEX
  • 2,624
  • 14
  • 43
  • 78

1 Answers1

2

This is what you need :

$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

DEMO

EXPLANATION:

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 “.” «\.»
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268