打印php标签和变量赋值作为文本

时间:2014-03-28 11:21:02

标签: php html string printing

假设我有这样的文字:

<?php

  $my_first_word = 'hi there';

  echo $my_first_word;

?>

我想把它打印到屏幕上,唯一的问题是当我把所有文字放在print"";

它实际上并没有打印php标签等,我希望它实际上是作为文本在浏览器上输出的。

4 个答案:

答案 0 :(得分:1)

我认为这应该有效:

echo htmlspecialchars($string);

http://docs.php.net/manual/en/function.htmlspecialchars.php

htmlspecialchars — Convert special characters to HTML entities

要打印新行的字符串,请添加以下内容:

nl2br(htmlspecialchars($string));

http://www.php.net/manual/en/function.nl2br.php

答案 1 :(得分:1)

$expand = 'appear';
echo 'Variables do not $expand $either'; // Outputs: Variables $expand
echo "Variables do not $expand $either"; // Outputs: Variables appear

答案 2 :(得分:0)

也许你可以试试:

print sprintf("%s", htmlspecialchars($my_first_word));

答案 3 :(得分:0)

作为文字:

echo '<?php

$my_first_word = \'hi there\';

echo $my_first_word;

?>';

as html:

echo nl2br(htmlspecialchars('<?php

$my_first_word = \'hi there\';

echo $my_first_word;

?>'));

请注意the use of '引用(otherwise变量不是文字),以及字符串中因此转义的'字符。