Regex with possible empty matches and multi-line match

后端 未结 4 1114
猫巷女王i
猫巷女王i 2021-01-23 22:28

I\'ve been trying to \"parse\" some data using a regex, and I feel as if I\'m close, but I just can\'t seem to bring it all home.
The data that needs parsing gener

4条回答
  •  梦谈多话
    2021-01-23 22:55

    So here's what I came up with using a tricky preg_replace_callback():

    $string ='FooID: 123456
    Name: Chuck
    When: 01/02/2013 01:23:45
    InternalID: 789654
    User Message: Hello,
    this is nillable, but can be quite long. Text can be spread out over many lines
    And can start with any number of \n\'s. It can be empty, too
    Yellow:cool';
    
    $array = array();
    preg_replace_callback('#^(.*?):(.*)|.*$#m', function($m)use(&$array){
        static $last_key = ''; // We are going to use this as a reference
        if(isset($m[1])){// If there is a normal match (key : value)
            $array[$m[1]] = $m[2]; // Then add to array
            $last_key = $m[1]; // define the new last key
        }else{ // else
            $array[$last_key] .= PHP_EOL . $m[0]; // add the whole line to the last entry
        }
    }, $string); // Anonymous function used thus PHP 5.3+ is required
    print_r($array); // print
    

    Online demo

    Downside: I'm using PHP_EOL to add newlines which is OS related.

提交回复
热议问题