2015-12-13 97 views
-2

我需要一個正則表達式來搜索數組,然後返回該鍵的值。我想獲得var1鍵的值。php正則表達式來搜索數組鍵和返回值

我的配置

<?php 

return [ 
    'var1' => 'test1', 
    'var2' => 'test2', 
    'var3' => 'test3' 
]; 

?> 

那麼它應該返回test1

+0

而這怎麼回事? – Utkanos

+3

爲什麼不像'echo $ array ['var1'];''爲你工作? – JakeGould

+0

@JakeGould因爲我想從文件中提取值,然後更新該值並將其插回到文件中。 – Tafelglotzer

回答

1

這是一個非正統的問題,但有足夠的一個直截了當的答案在這裏,並不需要一個正則表達式,所以我將介紹這個代替。

假設您的配置文件被稱爲config.php幷包含您在示例中提供的代碼片段:

<?php 

return [ 
    'var1' => 'test1', 
    'var2' => 'test2', 
    'var3' => 'test3', 
]; 

可以的includerequire返回值居然分配給一個變量。例如,在另一個腳本(假設你是在同一個目錄),你可以這樣做:

<?php 
// your config file... 
$file = __DIR__ . '/config.php'; 

// ensure the file exists and is readable 
if (!is_file($file) || !is_readable($file)) { 
    throw new RuntimeException(
     sprintf('File %s does not exist or is not readable!', $file) 
    ); 
} 

// include file and assign to variable `$config` 
// which now contains the returned array 
$config = include $file; 

echo 'original config:' . PHP_EOL; 
print_r($config); 

// update config key `var1` 
$config['var1'] = 'UPDATED!'; 

echo 'updated config:' . PHP_EOL; 
print_r($config); 

這產生了:

original config: 
Array 
(
    [var1] => test1 
    [var2] => test2 
    [var3] => test3 
) 
updated config: 
Array 
(
    [var1] => UPDATED! 
    [var2] => test2 
    [var3] => test3 
) 

我本來有點吃驚,你可以使用return外一個函數/方法的上下文,但它是完全有效的。您每天都會學到新的東西......此用例實際上記錄在include的文檔中 - 有關更多詳細信息,請參閱Example #5 include and the return statement

請注意,如果您使用includerequire來拉入不可信或外部腳本,則通常需要考慮安全因素。這在上面鏈接的文檔中討論過。此外,如果您的包含文件包含語法錯誤,那麼您可能會得到一個parse error或類似的,但我想這是一個明顯的觀點!

編輯

最後,我要指出,你的問題不問如何保存更新的配置迴文件,但你沒有發表評論下面這表明,要做到這一點也。

但是,如果要更新,並堅持在文件中的配置,我肯定會用寫一個更具延展性的方法/讀取這些數據/從磁盤 - 也許json_encode()json_decodeserialize()unserialize()

儘管如此,這裏是您可以在其中寫你的更新配置一個天真的解決方案:

// ... 

// file has to be writeable! 
if (!is_writeable($file)) { 
    throw new RuntimeException(
     sprintf('File %s is not writeable!', $file) 
    ); 
} 

file_put_contents($file, 
    sprintf('<?php return %s;', var_export($config, true))); 

延伸閱讀:

希望這有助於:)

+0

但我需要把它寫回配置文件不輸出它 – Tafelglotzer

+1

確實:)我注意到你在你的問題下評論了很多,並且我相應地更新了我的答案。讓我指出你的**問題**本身沒有具體說明 - 我會建議更新問題以包含該要求。 –

+0

謝謝你的作品,但它可以清理文件,我的意思是它不可讀? – Tafelglotzer