Search code examples
phpparsingstrip

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

Any help would be great! Thanks.


Solution

  • 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);