简体   繁体   English

PHP-回显颜色变量

[英]PHP - Echoing a variable in color

Im new to learning PHP as you might have guessed. 您可能已经猜到,我刚开始学习PHP。 I have the contents of a .txt file echoed but I would like it to stand out more, so I figured I would make it a different colour. 我回显了.txt文件的内容,但我希望它能脱颖而出,因此我认为我可以将其设置为其他颜色。

My code without colour: 我的代码没有颜色:

<?php
$file = fopen("instructions.txt", "r") or exit("Unable to open file");
while(!feof($file))
{
echo  fgets($file);
}
fclose($file);
?>

I have researched this and seen suggestions to others to use a div style, however this didn't work for me, it gave me red errors all the way down the page instead! 我已经对此进行了研究,并看到了其他人使用div样式的建议,但是,这对我没有用,而是在页面下方一直给我红色错误! I think its because I'm using 'fgets' not just a variable? 我认为这是因为我正在使用“ fgets”而不仅仅是一个变量吗? Is there a way to colour the echo red? 有没有办法将回声涂成红色?

The code I tried but doesn't work: 我尝试过但无法正常工作的代码:

echo "<div style=\"color: red;\">fgets($file)</div>";

(In general) You need to separate the actual PHP code from the literal portions of your strings. (通常)您需要将实际的PHP代码与字符串的文字部分分开。 One way is to use the string concatenation operator . 一种方法是使用字符串串联运算符. . Eg 例如

echo "<div style=\\"color: red;\\">" . fgets($file) . "</div>";

String Operators 字符串运算符

Other answer already told that you can't use a function call in a double quoted string. 其他答案已经告诉您,不能在双引号字符串中使用函数调用。 Let additionally mention that for formatting only tasks a <span> element is better suited than a <div> element. 另外要提到的是,对于仅格式化任务,与<div>元素相比, <span>元素更适合。

Like this: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span 像这样: https : //developer.mozilla.org/en-US/docs/Web/HTML/Element/span

You should try: 你应该试试:

<div style="color: red;"><?= fgets($file);?></div>

Note: <?= is an short hand method for <?php echo fgets($file);?> 注意: <?=<?php echo fgets($file);?>方法。

此版本不需要转义双引号:

echo '<div style="color:red;">' . fgets($file) . '</div>';

You can do this with the concatenate operator . 您可以使用串联运算符执行此操作. as has already been mentioned but IMO it's cleaner to use sprintf like this: 如前所述,但是IMO使用sprintf这样更干净:

echo sprintf("<div style='color: red;'>%s</div>", fgets($file));

This method comes into it's own if you have two sets of text that you want to insert a string in different places eg: 如果您有两组文本要在不同的位置插入字符串,则此方法将自己使用,例如:

echo sprintf("<div style='color: red;'>%s</div><div style='color: blue;'>%s</div>", fgets($file), fgets($file2));

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

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