User Agent iOS Version Number Detection Using Regular Expressions

If I have an iOS user agent like

Mozilla / 5.0 (iPhone, U, CPU iPhone OS 4_0, like Mac OS X, en-us) AppleWebKit / 532.9 (KHTML, e.g. Gecko) Version /4.0.5 Mobile / 8A293 Safari / 6531.22.7

or

Mozilla / 5.0 (iPhone, U, CPU iPhone OS 4_0, like Mac OS X, en-us) AppleWebKit / 532.9 (KHTML, e.g. Gecko) Mobile / 7D11

How can I detect an iOS version using regular expressions so that it returns, for example.

4.0

for the specified user agent?

+5
source share
4 answers

RegEx, which works for me, is:

/OS ((\d+_?){2,3})\s/

iPad 5.1.1 has HTTP_USER_AGENT, like this:

"Mozilla/5.0 (iPad; CPU OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3"

, 3 iOS iPhone OS.

Ruby :

def version_from_user_agent(user_agent)
  version = user_agent.match(/OS ((\d+_?){2,3})\s/)
  version = version[1].gsub("_",".") if version && version[1]
end

, iOS

+9

, :

/iPhone OS (\d+)_(\d+)\s+/

, , , ...

php :

$txt = 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7';
$reg = '/iPhone OS (\d+)_(\d+)\s+/';
$a   = array();
preg_match($reg, $txt, $a);

$str_version = $a[1].'.'.$a[2]; // This variable should now contain : 4.0 
+5

2 3 , 4.0 6.1.3

/\b[0-9]+_[0-9]+(?:_[0-9]+)?\b/

Javascript:

> navigator.userAgent
  "Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Mobile/10B146"
> navigator.userAgent.match(/\b[0-9]+_[0-9]+(?:_[0-9]+)?\b/);
  ["6_1_2"]

, , , iOS.

OS X Mac.

> navigator.userAgent
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1"
> navigator.userAgent.match(/\b[0-9]+_[0-9]+(?:_[0-9]+)?\b/);
  ["10_8_4"]

_ . .replace(/_/g,'.'); .split('_');.

_iOSDevice = !!navigator.platform.match(/iPhone|iPod|iPad/);
if(_iOSDevice)
 _iOSVersion = (navigator.userAgent.match(/\b[0-9]+_[0-9]+(?:_[0-9]+)?\b/)||[''])[0].replace(/_/g,'.');
+3

, - :

http://www.webapps-online.com/online-tools/user-agent-strings/dv/operatingsystem51849/ios

, :

(iPad|iPhone|iphone|iPod).*?(OS |os |OS\_)(\d+((_|\.)\d)?((_|\.)\d)?)

ios, x_y_z x.y.z, y z .

There are 7 lines of user agents that do not contain a version number, so these specific ones are not mapped. There is one sample line where the ios version is β€œ7.1”, but the regular expression matches only the major version number β€œ7” (that was enough for my use)

Like the tests on the page above, it was also tested against the ios10 agent strings listed on this page:

https://myip.ms/view/comp_browsers/1983/Safari_10.html

0
source

All Articles