PHP从文件中读取多行,不同的第一个单词

时间:2013-06-17 15:12:21

标签: php string file fopen

我试图从php中的txt文件中读取。我能够打开文件并逐行正确地显示它,但我想根据第一个单词做出决定。例如,如果在文本文件中该行以:

开头

Something1:这是一个测试

它将输出该字符串,但“Something1:”将为粗体,颜色不同于

Something2:这是test2

哪个也是粗体和颜色。所以我想说我希望标记为“Something1:”的所有内容都以粗体和红色输出,但我希望所有内容“Something2:”都输出粗体和绿色。无论如何要做到这一点。

$file = fopen($message_dir, "a+") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while (!feof($file))
{
    if (strpos(fgets($file), "Something1") == 0)
    {
        echo "<font color='#686868'><b>".fgets($file)."</b></font><hr />"."<br />";
    }
    else
    {
        echo "<font color='#fc0c87'><b>".fgets($file)."</b></font><hr />"."<br />";   
    }
}
fclose($file);

这是我的方向,但我确信有一种更简单的方法更有效。首先,这个粗体和颜色整个句子和第二个我认为fgets自动增量或者其他东西,因为它执行if语句然后它打印下一行而不是它执行if语句的那一行。但这是我的第一个想法,检查单词是否在字符串的位置0。

2 个答案:

答案 0 :(得分:0)

主要问题是fgets()每次调用它时都会读取另一行,因此如果您希望重用它,则需要将其值保存在中间变量中:

$line = fgets($file);

if (strpos($line, 'Something1') === 0) {
    $format = '<font color="#686868"><b>%s</b></font><hr /><br />';
} else {
    $format = '<font color="#fc0c87"><b>%s</b></font><hr /><br />';
}

echo sprintf($format, htmlspecialchars($line, ENT_QUOTES, 'UTF-8'));

另外,你是在追加模式下打开文件,但是你永远不会写它:

$file = fopen($message_dir, "r") or exit("Unable to open file!");

答案 1 :(得分:0)

你需要从文件中读取一个缓冲变量,每次从文件中读取新数据时,前面的文件都会“丢失”。

$file = fopen($message_dir, "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while (!feof($file))
{
    $currentLine = fgets($file);
    if (strpos($currentLine, "Something1") == 0)
    {
        echo "<font color='#686868'><b>$currentLine</b></font><hr /><br />";
    }
    else
    {
        echo "<font color='#fc0c87'><b>$currentLine</b></font><hr /><br />";   
    }
}
fclose($file);

我不会使用字体标记等,而是依赖于css:

$file = fopen($message_dir, "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
echo "<ul>\n";
while (!feof($file))
{
    $currentLine = fgets($file);
    if (strpos($currentLine, "Something1") == 0)
    {
        echo "<li class="Some1">$currentLine</li>\n";
    }
    else
    {
        echo "<li>$currentLine</li>\n";   
    }
}
echo "</ul>\n";
fclose($file);

由于您正在输出一个列表,我会使用一个无序列表并格式化像这样的chough css:

ul > li {
    color: #fc0c87;
    font-weight: bold;
    list-style: none;
}

ul > li.Some1 {
    color: #686868;
}

通过对ul > li规则进行适当更改,您可以利用css使用hr / br标记更好地调整外观。

相关问题