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

如何使用php解析字符串并将数据存储在数组中,php,string,parsing,Php,String,Parsing,我必须解析由不同值组成的字符串,然后将可能是其他字符串或数字的值存储在数组中 输入字符串示例: $inputString = 'First key this is the first value Second second value Thirt key 20394'; 我想创建一个数组,其中包含用于细分初始输入字符串的要查找的键。 包含关键字的数组可以如下所示: $arrayFind = array ('First key', 'Second', 'Thirt key'); 现在的想法是将

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

输入字符串示例:

$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');

有人能帮我吗?非常感谢

这里是一个快速而肮脏的代码片段

$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);
注意:这假定输入字符串中没有回车符


这可能不是最优雅的方式。还要注意,如果字符串中有重复的键,则将取最后一个值。

这是一个很糟糕的输入。如果第一个值是左第二条车道或类似的值,该怎么办?是否有分隔符?将键列表转换为正则表达式模式/first | second | Third/并使用preg|u split。是的,我知道这是一个糟糕的输入。。我没有定界符。唯一的固定值是$arrayFind中的字符串
<?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
)