Php使用sed或preg_replace从日志中删除特殊字符


Php removing special characters from log using sed or preg_replace

我正在使用这个AJAX日志文件Tailer&查看器:http://commavee.com/2007/04/13/ajax-logfile-tailer-viewer/它工作得很好,但在显示日志的页面上,它没有过滤任何特殊字符,所以看起来很乱。我试图修改logtail.php文件以清除特殊字符,但无法使其正常工作。

这是原始的logtail.php文件:

<?
// logtail.php
$cmd = "tail -50 /home/user/logfile.log";
exec("$cmd 2>&1", $output);
foreach($output as $outputline) {
 echo ("$outputline'n");
}
?>

这是我修改过的logtail.php文件,我试图在其中清除中的特殊字符

<?php
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);
$cmd = "tail -50 /home/user/logfile.log";
exec("$cmd 2>&1", $output);
foreach($output as $outputline) {
 exec('sed -r '.escapeshellarg("s/'x1B'[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g").' $output');
 echo ("$outputline'n");

}
?>

更新:我认为这应该采用原始输出,清除特殊字符,然后输出清除后的文本,但它不起作用,因为我仍然看到这样的垃圾:

[0;35;1m[something] text here[m

[something]部分很好,但[0;35;1m…[m需要离开。

您输出的是源代码行,而不是结果。

你的代码可能是这样的:

foreach($output as $outputline) {
 exec("echo '"$output'" | sed -r ".escapeshellarg("s/'x1B'[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"), $output);
 echo ("$outputline'n");
}

但这不会有效率

更好的是使用类似的preg_replace函数:

<?php
// logtail.php
$cmd = "tail -50 /home/user/logfile.log";
exec("$cmd 2>&1", $output);
$str = implode(''n', $output);
$result = preg_replace('/'x1B'[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/', '', $str);
echo ("$result'n");
?>