2016-12-04 242 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