2013-07-13 61 views
-1

我必須解析由不同值組成的字符串,然後將可能是其他字符串或數字的值存儲在數組中。輸入的如何使用php解析字符串並將數據存儲在數組中

例字符串:

$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

這是一個可怕的輸入一起工作。如果第一個值是「剩下的第二個車道」或類似的話,該怎麼辦? – JimL

+0

你有分隔符嗎? – DevZer0

+1

將你的密鑰列表轉換爲一個正則表達式模式'/ First | Second | Third /',並使用'preg_split()'作爲例子。 – mario

回答

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 
) 
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。另請注意,如果字符串中的鍵存在重複,則會取最後一個值。

相關問題