2017-08-10 49 views
0

这是我的UserAgent:地带用户代理PHP

的Mozilla/5.0(的PlayStation 4 4.73)为AppleWebKit/536.26(KHTML,例如 壁虎)

我想上述转换为该:

的PlayStation 4 4.73

我已经尝试了一些东西,如用substr剥离useragent,但那并没有解决 - 嗯,但它确实很慢,看起来并不专业。

什么是PHP中最好,最小和最快的方式来实现这个结果?

+0

您使用了哪些代码? – Andreas

+0

您需要首先定义所需字符串的规则。它是否找到了第一个括号?你想从这个UA字符串中得到什么:'Mozilla/5.0(Macintosh; Intel Mac OS X 10_9_5)AppleWebKit/537.36(KHTML,像Gecko)Chrome/59.0.3071.115 Safari/537.36'? –

+0

括号中的区域被称为评论。考虑到用户代理的格式,你可以做'preg_split('/ [()] /',$ userAgent)[1]'。但用户代理中的注释没有定义的结构。 – cmbuckley

回答

0

如果你只是想“无论是在第一对()括号” ......

$str = 'Mozilla/5.0 (PlayStation 4 4.73) AppleWebKit/536.26 (KHTML, like Gecko)'; 
$str = substr($str,strpos($str,'(')+1); // remove the first (and everything before it 
$str = substr($str,0,strpos($str,')')); // remove the first) and everything after it 
echo $str; 

如果你想更复杂的分析...(如果没有括号,或者只有一个如果你想抓住的字符串有(或)?如果你想要第一个括号中的内容,而不是第一个?),那么你将不得不做一些事情,呃编程...

+1

你知道你可以使子串行进入一行代码? – Andreas

+0

我可能会使用cmbuckley的解决方案,因为该解决方案使用起来有点短。 – Mitch

+0

@Mitch它可能更短,但也更重要的运行。万一你永远不需要再看这个代码,永远不需要改变它。这是Brett在他的回答中应该有的一个班轮。它像泥巴一样清晰。但它的工作。 '$ str = substr($ str,strpos($ str,'(')+ 1,strpos($ str,')') - strpos($ str,'(') - 1);'东西之前和之后在一行。https://3v4l.org/DmNUI – Andreas

0

这里有几种方法:

// smallest: 
$comment = preg_split('/[()]/', $userAgent)[1]; 

// fastest: 
$start = strpos($userAgent, '(') + 1; 
$comment = substr($userAgent, $start, strpos($userAgent, ')') - $start));