【问题标题】:PHP script to read text file and Highlight phrase in it用于读取文本文件并在其中突出显示短语的 PHP 脚本
【发布时间】:2014-03-11 12:25:03
【问题描述】:

如果涉及 PHP,我完全是菜鸟,所以提前感谢您的理解。

我的目标是将特定字符串从文本文件导出到网页,并用颜色突出显示搜索到的短语(如果短语为 FAIL,则为粗体红色,如果短语为 SUCCESS,则为粗体绿色)。

文件:

服务器:arch-linux SCHEDULED_TASK:SendFilesToValidate SUCCEEDED (0)

打印文件的一些代码:

<?php
$file = fopen("FINE.TXT","r");

while(! feof($file))
{
    $file .= fgets($file). "<br />";
    $body_text= $file ;
    $searh_letter = 'FAILED'; 
    echo fgets($file). "<br />";
    echo '';
}

如您所见,我正在尝试将计划任务的结果导出到文本文件,然后导出到网页。我应该解决什么问题才能使其按预期工作?

【问题讨论】:

    标签: php text colors formatting webpage


    【解决方案1】:

    这会让您第一次出现 FAIL 或 SUCCESS。

    $fileContent = file_get_contents("FINE.TXT");
    if (($pos = strpos("FAIL", $fileContent)) !== false) {
        echo "<p class='fail'>".substr($fileContent, $pos, 4)."</p>";
    } elseif (($pos = strpos("SUCCESS", $fileContent)) !== false) {
        echo "<p class='success'>".substr($fileContent, $pos, 7)."</p>";
    } else {
        echo "phrase not found";
    }
    

    如果您的 txt 文件的每一行都可能出现 FAIL 或 SUCCESS,请使用:

    $file = file("FINE.TXT");
    foreach ($file as $line) {
        if (($pos = strpos("FAIL", $line)) !== false) {
            echo "<p class='fail'>".substr($line, $pos, 4)."</p>";
        } elseif (($pos = strpos("SUCCESS", $line)) !== false) {
            echo "<p class='success'>".substr($line, $pos, 7)."</p>";
        }
    }
    

    【讨论】:

    • 更新:我从所有已回答的建议中都没有得到任何输出,可能是什么问题?
    【解决方案2】:

    最好的解决方案恕我直言:

    <?php
    

    $content = file_get_contents("file.txt"); $content = str_replace("成功", 'SUCCEEDED (0)', $content); $content = str_replace("失败", '失败 - 请调查', $content); $content = str_replace("SERVER:", 'SERVER > ', $content); $content = str_replace("TASK:", 'TASK_NAME = ', $content); $content = str_replace("SERVERNAMED@AD", 'SERVERNAMED@AD \ ', $content); $content = str_replace("SERVERNAMED@AD", 'SERVERNAMED@AD \ ', $content); echo nl2br($content);

    ?>

    【讨论】:

      【解决方案3】:

      这是一个非常简单的方法。
      但请注意 PHP 区分大小写:

      “成功”!=“成功”

      $content = file_get_contents("FINE.TXT");
      $content = str_replace("Success", '<span style="font-weigt: bold; color: green; ">Success</span>', $content);
      $content = str_replace("Failed", '<span style="font-weigt: bold; color: red; ">Failed</span>', $content);
      echo $content;
      

      【讨论】:

      • 更新:我从所有已回答的建议中都没有得到任何输出,可能是什么问题?
      • 更新:这个有效,我无法将输出逐行打印...
      猜你喜欢
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      • 1970-01-01
      相关资源
      最近更新 更多