-1

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

输入字符串示例:

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

任何人都可以帮助我吗?非常感谢

4

2 回答 2

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

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

于 2013-07-13T15:24:34.107 回答
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
)
于 2013-07-13T15:30:05.777 回答