phpstringsplittext-extractiontext-parsing

Parse multiline text with values of static or maximum length and with multiple delimiters


I have data which I wish to be pasted into a textbox, it will be in the following form.

Ryu Aiter D78:21:87:13 177 /177 1 / 6
Ryu Chronos D78:21:26:21 182 /182 0 / 6
Ryu Hermes D78:21:26:22 201 /201 0 / 6
Ryu Hefaistos D78:31:75:10 136 /136 1 / 2
Ryu Krotos D78:84:96:11 170 /170 1 / 6
Ryu Heros D78:65:51:31 175 /175 2 / 5
Ryu Arachnos D78:13:84:11 185 /185 0 / 5

It's split up like this:

What I wish to do is create a loop for each Row of text, and then inside that loop chop out each part of the row into variables for each component.

As far as ideas on separating it I know that the : symbol is banned from names and bases. So if I find the first ":" then step back 2 and take the next 12 chars that is my location. I know that can be done with a loop and check if ($string[$x] === ':').

But how do I loop through the lines? And how can I separate the rest of the data in each line?


Solution

  • This is what regular expressions are for :P try this out:

    $lines = explode( "\r\n", $data );
    
    $users = array();
    
    foreach( $lines as $line )
    {
        $matches = array();
        $user = array();
    
        preg_match( "/([^ ]+) ([^ ]+) ((?:[A-Z])(?:[0-9]+:){3}[0-9]+) ([0-9]+) \/([0-9]+) ([0-9]+) \/ ([0-9]+)/", $line, $matches );
    
        list(,$user['name'],$user['base'],$user['location'],$user['econ'],$user['maxecon'],$user['used'],$user['total']) = $matches;
    
        $users[] = $user;
    }
    

    You will have an array called users which contains a series of associative arrays with the components. Like below...

    Array
    (
    [0] => Array
        (
            [total] => 6
            [used] => 1
            [maxecon] => 177
            [econ] => 177
            [location] => D78:21:87:13
            [base] => Aiter
            [name] => Ryu
        )
    
    [1] => Array
        (
            [total] => 6
            [used] => 0
            [maxecon] => 182
            [econ] => 182
            [location] => D78:21:26:21
            [base] => Chronos
            [name] => Ryu
        )
    
    etc, etc...
    

    EDIT: I made a lot of assumptions about the data as you haven't given many details, if you need further help with the expression let me know.

    UPDATE AS PER YOUR COMMENT:

    Line 182: $name = htmlspecialchars(mysql_real_escape_string($_POST['name']));
    Line 188: $tecon = htmlspecialchars(mysql_real_escape_string($user['econ']));
    

    You should turn on display_errors as they were simple syntax errors that could easily be debugged.