PHP - 如何解析文本字符串并查找键值

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");
<?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 )

Tested in PHP 5.3:

    // set-up test string and final array
    $myString = "@test1: test1;@test2: test2;";
    $myArr = array();

    // do the matching
    preg_match_all('/@([^\:]+)\:([^;]+);/', $myString, $matches);

    // put elements of $matches in array here
    $actualMatches = count($matches) - 1;
    for ($i=0; $i<$actualMatches; $i++) {
        $myArr[$matches[1][$i]] = $matches[2][$i];
    }
    print_r($myArr);

The reasoning behind this is this:

  1. The regex is creating two capture groups. One capture group is the key, the other the data for that key. The capture groups are the portions of the regex inside left and right bananas, i.e., (...).
  2. $actualMatches just adjusts for the fact that preg_match_all returns an extra element containing all matches lumped together.

Demo.

You can try looping the string line by line (explode and foreach) and check if the line starts with an @ (substr) if it has, explode the line by :.

http://php.net/manual/en/function.explode.php

http://nl.php.net/manual/en/control-structures.foreach.php

http://nl.php.net/manual/en/function.substr.php

Depending on what your input string looks like, you might be able to simply use parse_ini_string, or make some small changes to the string then use the function.