2016-02-20 46 views
1

提取哈希我有這個格式的文件:正則表達式從文件

5:Name: {"hash":"c602720140e907d715a9b90da493036f","start":"2016-02-20","end":"2016-03-04"} 
5:Name: {"hash":"e319b125d71c62ffd3714b9b679d0624","sa_forum":"on","start":"2015-11-14","end":"2016-02-20"} 

我試圖提取使用正則表達式的哈希鍵和日期。 我該怎麼辦?

我試過這個/^[a-z0-9]{32}$/的散列,但它不起作用。

我將不勝感激。

編輯:這是一個文本文件,我試圖preg_match()它。這是我的代碼:

$file = file_get_contents("log.txt"); 

preg_match("/^[a-z0-9]{32}$/",$file, $hashes); 
var_dump($hashes); 

我得到一個空數組。

+1

看起來像是一個JSON ...解碼它:'json_deocde($ string,true);' –

+0

不,它不是json。它是一個txt文件。嘗試preg_match它。 – Thenis

+0

請顯示您的代碼以匹配它。 – Will

回答

2

的問題是,你在你的邊界匹配^$,但你真的想在字符串中間匹配的東西。試試這個:

/(?<=")[a-f0-9]{32}(?=")/ 

這隻會在引號之間匹配。此外,您不需要a-z,因爲它只能是a-f

而且,既然你想的所有散列值的文件而不是一個數組中,你需要preg_match_all()

php > $file = file_get_contents("hashfile.txt"); 
php > preg_match_all('/(?<=")[a-f0-9]{32}(?=")/', $file, $matches); 
php > var_dump($matches); 
array(1) { 
    [0]=> 
    array(2) { 
    [0]=> 
    string(32) "c602720140e907d715a9b90da493036f" 
    [1]=> 
    string(32) "e319b125d71c62ffd3714b9b679d0624" 
    } 
} 
php > 

的匹配存儲陣列$matches[0]在我上面的例子。