开发者

Strip Down A String at Colon

I have a textarea where a user copies and pastes the entire message:

Time(UTC): 2010-02-27T21:58:20.74Z

Filesize  : 9549920 bytes

IP Address: 192.168.1.100

IP Port: 59807

Using PHP, how can I automate this and parse this down to 4 separate variables, like so:

<?php
$time = 2010-02-27T21:58:20.74Z;
$filesize = 9549920;
$ip = 192.168.1.100;
$port = 59807;

I can tell that each line has a colon, so I'm thinking this might have something to do with it. I'm not sure if I would n开发者_如何学运维eed to use substr or something. But I'm not quite sure where to start with this?

Any help would be great! Thanks.


one way

$textarea=<<<EOF
Time(UTC): 2010-02-27T21:58:20.74Z

Filesize  : 9549920 bytes

IP Address: 192.168.1.100

IP Port: 59807
EOF;

$s = explode("\n\n",$textarea);
foreach ($s as $k=>$v){
  list($a,$b) = array_map(trim,explode(": ",$v));
  # or use explode(":",$v,2) as jason suggested.
  $array[$a]=$b;
}
print_r($array);


Is it guaranteed that each will be on its own line and in that order? Then you might be able to explode the entire string on \n and then explode each line on :. That's a quick and dirty approach. Beyond that you should go through line by line and look at the beginning of the line whether the text before the first colon matches a desired variable and, if so, parse it according to predetermined parsing rules (e.g. drop 'bytes' from the filesize value).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜