分析文本并从每行两个子字符串填充关联数组


Parse text and populate associative array from two substrings per line

给定一个大的文本字符串,我想搜索以下模式:

@key: value

例如:

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

输出应为:

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

链接http://ideone.com/fki3U

阵列([第一]=>第一个值[秒]=>秒值(

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

背后的原因是:

  1. regex正在创建两个捕获组。一个捕获组是关键其他键的数据。捕获组是正则表达式的部分在左右香蕉内部,即(…(
  2. $actualMatches只是根据preg_match_all返回包含所有匹配项的额外元素

演示。

匹配从@开始到;结束的所有符合条件的行。

捕获不包含任何冒号的子字符串作为第一组,并捕获冒号后面的空格和行尾分号之间的子字符串。

通过使用第二个捕获组中的任意字符点,子字符串可以包含分号,而不会损坏任何提取的数据。

调用array_combine(),形成两个捕获组之间的键值关系。

代码:(演示(

preg_match_all(
    '/^@([^:]+): (.+);$/m',
    $text,
    $m
);
var_export(array_combine($m[1], $m[2]));

输出:

array (
  'first' => 'first-value',
  'second' => 'second-value',
)

您可以尝试逐行循环字符串(分解和foreach(,并检查该行是否以@(substr(开头。

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

根据输入字符串的外观,您可以简单地使用parse_ini_string,或者对字符串进行一些小的更改,然后使用函数。