I've been investigating various user agent parsers and have been surprised at the complexity and size required.

If I'm only interested in parsing for the OS into three categories: Windows, Mac, or Other — how can I do this efficiently, lightly, and quickly?

I don't care about browsers, versions, or anything else. Just Mac, Windows or Other.

What do you recommend?

Here's what I have so far:

if (strpos($user_agent, 'Windows')) $os = 'Windows';
elseif (strpos($user_agent, 'Macintosh')) $os = 'Macintosh';
else $os = 'Other';

Any danger in this straight forward approach?

有帮助吗?

解决方案

This might not be enough. Older Windows versions tend to have WinNT prefix instead. Looking for Win only also match non-windows user agents. Also for Macintosh, search for Mac only. Usually it is listed as Mac OS in user agents.

This is a good reg exp for Windows detection:

/Win(?:dows )?([^do]{2})\s?(\d+\.\d+)?/
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top