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

时间:2011-10-23 21:45:50

标签: php regex

给定大量文本,我想搜索以下模式:

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

4 个答案:

答案 0 :(得分:3)

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

  

阵列(       [first] =&gt;第一价值       [second] =&gt;第二价值)

答案 1 :(得分:1)

在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. 正则表达式创建了两个捕获组。一个捕获组是关键,    该密钥的其他数据。捕获组是正则表达式的一部分    在左右香蕉里面,即(...)。
  2. $actualMatches只是调整preg_match_all返回的事实    包含所有匹配的额外元素。
  3. Demo

答案 2 :(得分:0)

您可以尝试逐行循环字符串(explode和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

答案 3 :(得分:0)

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

相关问题