这是我的UserAgent:地带用户代理PHP
的Mozilla/5.0(的PlayStation 4 4.73)为AppleWebKit/536.26(KHTML,例如 壁虎)
我想上述转换为该:
的PlayStation 4 4.73
我已经尝试了一些东西,如用substr剥离useragent,但那并没有解决 - 嗯,但它确实很慢,看起来并不专业。
什么是PHP中最好,最小和最快的方式来实现这个结果?
这是我的UserAgent:地带用户代理PHP
的Mozilla/5.0(的PlayStation 4 4.73)为AppleWebKit/536.26(KHTML,例如 壁虎)
我想上述转换为该:
的PlayStation 4 4.73
我已经尝试了一些东西,如用substr剥离useragent,但那并没有解决 - 嗯,但它确实很慢,看起来并不专业。
什么是PHP中最好,最小和最快的方式来实现这个结果?
如果你只是想“无论是在第一对()括号” ......
$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;
如果你想更复杂的分析...(如果没有括号,或者只有一个如果你想抓住的字符串有(或)?如果你想要第一个括号中的内容,而不是第一个?),那么你将不得不做一些事情,呃编程...
这里有几种方法:
// smallest:
$comment = preg_split('/[()]/', $userAgent)[1];
// fastest:
$start = strpos($userAgent, '(') + 1;
$comment = substr($userAgent, $start, strpos($userAgent, ')') - $start));
您使用了哪些代码? – Andreas
您需要首先定义所需字符串的规则。它是否找到了第一个括号?你想从这个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'? –
括号中的区域被称为评论。考虑到用户代理的格式,你可以做'preg_split('/ [()] /',$ userAgent)[1]'。但用户代理中的注释没有定义的结构。 – cmbuckley