Search code examples
phpregexassociative-arraytext-parsing

Parse text and populate associative array from two substrings per line


Given a large string of text, I want to search for the following patterns:

@key: value

So an example is:

some crazy text
more nonesense
@first: first-value;
yet even more non-sense
@second: second-value;
finally more non-sense

The output should be:

array("first" => "first-value", "second" => "second-value");

Solution

  • <?php
    
    
    $string = 'some crazy text
    more nonesense
    @first: first-value;
    yet even more non-sense
    @second: second-value;
    finally more non-sense';
    
    preg_match_all('#@(.*?): (.*?);#is', $string, $matches);
    
    $count = count($matches[0]);
    
    for($i = 0; $i < $count; $i++)
    {
        $return[$matches[1][$i]] = $matches[2][$i];
    }
    
    print_r($return);
    
    ?>
    

    Link http://ideone.com/fki3U

    Array ( [first] => first-value [second] => second-value )