2013-02-25 72 views
1

我試圖像這樣來解析包含空格分隔的密鑰=>值對文件,格式:PHP等效Python的shlex.split的

host=db test="test test" blah=123 

通常,該文件是由Python和攝取使用shlex.split解析,但我一直無法找到一個PHP的等價物,我試圖用preg_splitstrtok進行邏輯處理的嘗試效率不高。

是否有一個PHP等價於Python的shlex.split

+0

據我所知,沒有函數會產生你正在尋找的確切行爲,但是,這兩步應該是微不足道的。您可以使用'preg_match_all'將字符串分解成一個數組,然後遍歷數組,將其轉換爲您需要的格式。 – datasage 2013-02-25 19:24:47

+0

類似於[用於匹配名稱值對的正則表達式](http://stackoverflow.com/questions/168171/regular-expression-for-parsing-name-value-pairs),用','替換爲'\ s '將允許preg_match_all工作。 – mario 2013-02-25 19:28:27

回答

2

不幸的是,沒有內置的PHP函數可以本地處理這樣的分隔參數。不過,你可以使用一點正則表達式和一些數組散步來快速創建一個。這只是一個例子,只適用於您提供的字符串類型。任何額外的條件將需要被添加到正則表達式,以確保它正確地匹配模式。在遍歷文本文件時,可以輕鬆調用此函數。

/** 
* Parse a string of settings which are delimited by equal signs and seperated by white 
* space, and where text strings are escaped by double quotes. 
* 
* @param String $string String to parse 
* @return Array   The parsed array of key/values 
*/ 
function parse_options($string){ 
    // init the parsed option container 
    $options = array(); 

    // search for any combination of word=word or word="anything" 
    if(preg_match_all('/(\w+)=(\w+)|(\w+)="(.*)"/', $string, $matches)){ 
     // if we have at least one match, we walk the resulting array (index 0) 
     array_walk_recursive(
      $matches[0], 
      function($item) use (&$options){ 
       // trim out the " and explode at the = 
       list($key, $val) = explode('=', str_replace('"', '', $item)); 
       $options[$key] = $val; 
      } 
     ); 
    } 

    return $options; 
} 

// test it 
$string = 'host=db test="test test" blah=123'; 

if(!($parsed = parse_options($string))){ 
    echo "Failed to parse option string: '$string'\n"; 
} else { 
    print_r($parsed); 
} 
+0

這是一個非常糟糕的答案,相當於'shlex.split'。因爲它甚至不能把'a「b c」'處理成'[「a」,「b c」]'。 – Vallentin 2016-03-26 13:46:49