tags:

views:

67

answers:

2

Hi all,

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 need to use substr or something. But I'm not quite sure where to start with this?

Any help would be great! Thanks.

+3  A: 

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);
ghostdog74
The first line has more than one colon. I don't think you'll get all of the value that way.
Alex JL
yes, you are right, i missed that. thks.
ghostdog74
You would if you did `explode(':', $v, 2)` though.
jasonbar
yes, that's another way. thks
ghostdog74
Thanks for the reply. I'm trying to do this when submitting a form. And when I do so, it appears that the \n is not being submitted/passed. I even tried $textarea = nl2br($_POST['textarea']; Any ideas on how to make sure the \n is being passed?
Dodinas
you can look at the docs on nl2br :http://php.net/manual/en/function.nl2br.php. I think someone has written the opposite of nl2br. you can try that
ghostdog74
+2  A: 

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).

pr1001
Ok, ghostdog gave you actual code describing my first solution.
pr1001