我正在阅读一种用php编写的纺织品,其中有两句话。
Top 1: 201 秘密
前 4 名 : 203, 290, 593, 224
多么美好的生活!, 魔法, 独角兽之地, 火
function getcontent($file1){
$fh= fopen($file1, 'r');
$theData = fread($fh, filesize("$file1"));
return $theData;
fclose($fh);
}
?>
当我回显文件时,我希望以不同的颜色突出显示 2 个句子:
<div align="center"><h4 style="line-height:150%;"><?php echo "<pre>" .$movies. "</pre>"; ?></h5></div>
$movies是文本文件。如何在 php 中做到这一点?我必须为此创建一个单独的函数吗?
PHP的file_get_contents函数是获取文件内容的更简单方法。
如果你的文件只有 2 行,可能有一种更简单的方法可以做到这一点,但你可以通过爆炸来分割行(有关可能有奇怪换行符的爆炸文本的详细信息,请尝试此处),如下所示:
$movies = file_get_contents("filename.txt");
$lines = explode("'n", $movies);
然后根据需要循环浏览线条和样式:
if (is_array($lines)) {
$line_count = count($lines);
for ($i = 0; $i <= $line_count; $i++) {
if ($i % 2 == 0) {
echo '<span style="color: red;">' . $lines[$i] . '</span><br>';
}
else {
echo '<span style="color: blue;">' . $lines[$i] . '</span><br>';
}
}
}
如果文件中有超过 2 行,则可以实现更详细的逻辑以不同的方式为线条着色。
根据您的注释,以下代码会将第一行着色为红色,将所有其他行着色为蓝色:
if (is_array($lines)) {
$line_count = count($lines);
for ($i = 0; $i <= $line_count; $i++) {
if ($i == 0) {
echo '<span style="color: red;">' . $lines[$i] . '</span><br>';
}
else {
echo '<span style="color: blue;">' . $lines[$i] . '</span><br>';
}
}
}
您可以使用数组来存储不同的句子,因此新代码将是这样的。顺便说一下,返回语句之后的代码永远不会执行,所以要避免这样做
function getcontent($file1)
{
$lines = file($file); //read all lines to array
return $lines;
}
<div align="center">
<h4 style="line-height:150%;">
<?php
//lines is the array returned from getcontent
foreach($lines as $line)
{
echo "<pre>" .$line. "</pre>"
}
?>
</h5>
</div>
之后,您可以使用 if 子句交换颜色,以便每行都有交替的颜色,或者如果您愿意,可以使用随机颜色