-4

我想知道我应该如何使用正则表达式将其拆分为一个数组:

input = "1254033577 2009-09-27 06:39:37 "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_4_11; en) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/3.2.1 Safari/525.27.1" 44.12.96.2      Duncan  OK  US  Hot Buys    http://www.esshopzilla.com/hotbuys/     http://www.google.com/search?hl=en&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=Zk5&q=ipod&aq=f&oq=&aqi=g-p1g9"

array (
  1254033577, 
  2009-09-27 06:39:37, 
  Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_4_11; en) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/3.2.1 Safari/525.27.1, 44.12.96.2, 
  Duncan, 
  OK,
  US, 
  Hot Buys,
  http://www.esshopzilla.com/hotbuys/, 
  http://www.google.com/search?hl=en&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=Zk5&q=ipod&aq=f&oq=&aqi=g-p1g9"
)
4

2 回答 2

3

您可以尝试调整如下内容:

$pattern = '~(?<id>\d++)'                                        . '\s++'
         . '(?<datetime>\d{4}-\d{2}-\d{2}\s++\d{2}:\d{2}:\d{2})' . '\s++"'
         . '(?<useragent>[^"]++)'                                . '"\s++'
         . '(?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'           . '\s++'
         . '(?<name>\S++)'                                       . '\s++'
         . '(?<response>[A-Z]++)'                                . '\s++'
         . '(?<country>[A-Z]{2,3})'                              . '\s++'
         . '(?<title>(?>[^h\s]++|\s*+(?>h(?!ttp://))?|\s++)+)'   . '\s++'
         . '(?<url>\S++)'                                        . '\s++'
         . '(?<search>\S++)~';

preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);

foreach($matches as $match) {
    echo '<br/>id: '         . $match['id']        . '<br/>datetime: ' . $match['datetime']
       . '<br/>user agent: ' . $match['useragent'] . '<br/>ip: '       . $match['ip']
       . '<br/>name: '       . $match['name']      . '<br/>response: ' . $match['response']
       . '<br/>country: '    . $match['country']   . '<br/>title: '    . $match['title']
       . '<br/>url: '        . $match['url']       . '<br/>search: '   . $match['search'] 
       . '<br/>';
}

注意:您可以将您期望的所有字段放在一个数组中并减少代码的大小。

于 2013-07-27T20:42:58.317 回答
0

Your problem isn't that you're trying to split a string into an array with various delimiters.

Your problem is that you're trying to do browser detection from the user agent string.

For every programming problem you have, ask yourself "Is this something that others might already have had, and that I might take advantage of their solutions?"

If so, then try Googling for the answer. In this case, I Googled for "php parse user agent". That search led me to this page on StackOverflow which led me to this function that is built in to PHP itself.

于 2013-07-28T01:29:31.127 回答