如何使用php解析字符串并将数据存储在数组中

时间:2013-07-13 14:34:02

标签: php string parsing

我必须解析由不同值组成的字符串,然后将可能是其他字符串或数字的值存储在数组中。

输入的示例字符串:

$inputString = 'First key this is the first value Second second value Thirt key 20394';

我想创建一个包含要查找的键的数组,以细分我的初始输入字符串。 具有关键字的数组可以如下所示:

$arrayFind = array ('First key', 'Second', 'Thirt key');

现在的想法是将$ arrayfind从开始循环到结束并将结果存储在新数组中。我需要的结果数组如下:

$result = array(
                'First key'=>'this is the first value', 
                'Second' => 'second', 
                'Thirt val' => '20394');

有人可以帮助我吗?非常感谢你

2 个答案:

答案 0 :(得分:1)

这是一个快速而又脏的代码片段。

$inputString = 'First key this is the first value Second second value Thirt key 20394';
$tmpString = $inputString;
$arrayFind = array ('First key', 'Second', 'Thirt key');
foreach($arrayFind as $key){
    $pos = strpos($tmpString,$key);
    if ($pos !== false){
        $tmpString = substr($tmpString,0,$pos) . "\n" . substr($tmpString,$pos);
    }
}
$kvpString = explode("\n",$tmpString);
$result = array();
$tCount = count($kvpString);
if ($tCount>1){
    foreach ($arrayFind as $f){
        for ($i=1;$i<$tCount;$i++){
            if (strlen($kvpString[$i])>$f){
                if (substr($kvpString[$i],0,strlen($f))==$f){
                    $result[$f] = trim(substr($kvpString[$i],strlen($f)));
                }
            }
        }
    }
}
var_dump($result);

注意:这假设输入字符串中没有回车\n

这可能不是最优雅的方式。另请注意,如果字符串中存在重复键,则将采用最后一个值。

答案 1 :(得分:1)

<?php
error_reporting(E_ALL | E_STRICT);

$inputString = 'First key this is the first value Second second value Thirt key 20394';
$keys = ['First key', 'Second', 'Thirt key'];

$res = [];
foreach ($keys as $currentKey => $key) {
    $posNextKey = ($currentKey + 1 > count($keys)-1) // is this the last key/value pair?
                  ? strlen($inputString) // then there is no next key, we just take all of it
                  : strpos($inputString, $keys[$currentKey+1]); // else, we find the index of the next key
    $currentKeyLen = strlen($key);
    $res[$key] = substr($inputString, $currentKeyLen+1 /*exclude preceding space*/, $posNextKey-1-$currentKeyLen-1 /*exclude trailing space*/);
    $inputString = substr($inputString, $posNextKey);
}

print_r($res);
?>

输出:

Array
(
    [First key] => this is the first value
    [Second] => second value
    [Thirt key] => 20394
)