2016-12-04 253 views
1

其目的是通過從磁盤讀取文件到字符串(追加\ n \ n),截斷聊天記錄到最多100行(每增加一行時),然後使用截斷函數preg_匹配最多100行的模式並返回該匹配的第一個實例,然後將匹配寫入文件。php截斷使用grep preg_match

這一切都沒有截斷功能。 preg_match模式在TextWrangler文件中正確選擇。但是,如圖所示添加截斷函數會導致刪除整個文本。

$existing= file_get_contents('LOG.txt') ; 
// get new text-line $addnew from POST 
$addnew=$addnew."\n\n"; 
$newlog = $addnew.$existing ; 
$newlog = truncate ($newlog) ; 
file_put_contents('LOG.txt',$newlog); 

function truncate ($string) { 
    preg_match('#^[(.*?)\n\n]{0,100}#',$string,$match); 
    if (isset ($match[0])) { 
     $string=$match[0]; 
    } 
    return $string ; 
} 

這說明什麼需求?謝謝。

+0

不要使用字符類,使用來代替:'^(。*?\ n \ n){0,100}' – Toto

+0

完美。謝謝。 – Andante88

+0

這與UNIX工具'grep'有什麼關係?如果答案沒有,就像它似乎是,那麼請[編輯]您的問題,以刪除該標籤。 –

回答

0

^[(.*?)\n\n]{0,100}是一個字符類,它是指0至100中的任何的(.*?)\n

我想你想:

preg_match('#^(.*?\n\n){0,100}#',$string,$match) 
+0

完美。謝謝。 – Andante88

+0

@ Andante88:不客氣,很高興幫助 – Toto