0

Here is the string I have from a server:

70.90.184.9 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

The data I need pulled out should be like this:

$ip = "70.90.184.9"
$os = "Intel Mac OS X 10_8_4"

Is there a RegEx to get the IP out easily in PHP? And what about the OS?

Thanks!

3 Answers 3

2

Use the function get_browser() for this. It's a hidden treasure ;) Call:

$str = '70.90.184.9 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';
var_dump(get_browser($str));
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not a big fan of depending on browscap.ini. It relies on user updates to keep the database current. I'm more looking to do the parsing myself just for the single string as shown.
I could give you a regex especially for that string, but as @Sverri pointed out, user agents are unreliable at all..
2

Use the PHPBrowsCap project. It is a stand-alone class that tries to get around the limitations of the get_browser() function.

Parsing user agent strings is notoriously difficult and unreliable. The aforementioned project is probably the best way of getting usable user agent information. That being said, please do not use user agent strings to put up "This website only supports browser X" messages -- people will hate you for it.

3 Comments

This sounds interesting. +1
"please do not use user agent strings to put up 'This website only supports X browser' messages" - This is not my intent, don't worry.
Unfortunately it looks like this won't work for me either. With a user agent string of iPhone OS 6_1_4 the PHPBrowsCap project displays it as iOS version 6.1. I need the full 6.1.4.
0

This pattern do the job for your example, but i am not sure that it will be the same for an another string:

^([\d.]++)[^(]++\(\S++\s([^)]++)

If you want a more general pattern, please update your post with some possible examples which can be useful to determine a more global syntaxe. However, regex alternatives as Sverri suggests is perhaps a good way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.