首页 > 解决方案 > 如何突出显示要下载的文件中的字符串?

问题描述

我有一个文本文件“output.txt”,它是 shell 命令的输出。我想突出显示该文件中作为 $_GET['word'] 的某些单词,然后允许使用 href 下载。

我已经看到了多个问题,但在这种情况下似乎没有一个问题有效。

  1. 突出显示给定字符串中的多个关键字
  2. 突出显示字符串中的单词,如果它包含关键字

代码:

$cmd = shell_exec("/usr/local/bin/clustalw2 -infile=input.txt -tree -type=protein -case=upper &");
$file = 'output.txt';
$content = explode("\n",file_get_contents("output.txt"));
$keyword = $_GET['word'];
$content = str_replace($keyword,'<span style="color:red">'.$keyword.'</span>',$content);
$file = file_put_contents($file, $content);
echo "<a href='http://some.thing.com/folder/output.txt'>Download Result file</a>";

它既没有突出显示文本也没有给出任何错误。

标签: phphighlight

解决方案


我怀疑问题在于打开初始文件。以下确实对我有用。

我创建了/home/input.txt:

this is a test
that may
or may not work.

然后跑:

$cmd = shell_exec(" cp /home/input.txt output.txt");
$file = 'output.txt';
$content = explode("\n",file_get_contents("output.txt"));
$keyword = "may";
$content = str_replace($keyword,'<span style="color:red">'.$keyword.'</span>',$content);
$file = file_put_contents($file, implode("\n", $content));
echo "<a href='http://some.thing.com/folder/output.txt'>Download Result file</a>";

output.txt 现在是:

this is a test
that <span style="color:red">may</span>
or <span style="color:red">may</span> not work.

推荐阅读