简体   繁体   English

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

[英]Php removing special characters from log using sed or preg_replace

I'm using this AJAX Logfile Tailer & Viewer: http://commavee.com/2007/04/13/ajax-logfile-tailer-viewer/ It works well but on the page where the log is being displayed it isn't filtering any special characters so it looks messy. 我正在使用此AJAX日志文件剪裁程序和查看器: http : //commavee.com/2007/04/13/ajax-logfile-tailer-viewer/效果很好,但是在显示日志的页面上却没有过滤任何特殊字符,使其看起来很凌乱。 I'm trying to modify the logtail.php file to clean out the special characters but can't quite get it working. 我正在尝试修改logtail.php文件以清除特殊字符,但无法完全正常工作。

Here is the original logtail.php file: 这是原始的logtail.php文件:

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

Here is my modified logtail.php file in which I am attempting to clean out the special characters from: 这是我修改后的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");


}
?>

Update: I think this should take the original output, clean out the special characters, and then output the cleaned up text, but it doesn't work as I still see junk like this: 更新:我认为这应该采用原始输出,清除特殊字符,然后输出清除的文本,但是它不起作用,因为我仍然看到像这样的垃圾:

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

The [something] part is fine but the [0;35;1m ... [m needs to go. [某物]部分很好,但[0; 35; 1m ... [m需要走。

You outputting the source line instead of resulting. 您输出的是源行,而不是结果行。

Your code could be like that: 您的代码可能像这样:

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");
}

But this will be not efficient. 但这不会有效。

Better is to use preg_replace function like that: 更好的方法是使用像这样的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");
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM