Store specific data in a variable from another variable with regular expression with PHP

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 really don’t know how to get the code correctly, and the part after the $ version is a hunch. can anyone help me? Maybe with preg_split? I want 4.4.2 to be stored in $ version.

+2
php regex
Apr 11 '15 at 22:51
source share
1 answer

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 "." «\.» 
+2
Apr 11 '15 at 22:58
source share



All Articles