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

Assume I have this text:

<?php

  $my_first_word = 'hi there';

  echo $my_first_word;

?>

And I want to print it out to the screen, only problem is when I put all the text inside a print"";

It doesn't actually print the php tags and etc, I want it to actually be outputted on the browser as text.

as text:

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;

?>'));

Do note the use of ' for quoting (otherwise the variables would not be literals), as well as the therefore escaped ' char inside the string.

I think this should work:

echo htmlspecialchars($string);

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

htmlspecialchars — Convert special characters to HTML entities

For string to print new line add this:

nl2br(htmlspecialchars($string));

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

maybe you can try:

print sprintf("%s", htmlspecialchars($my_first_word));
$expand = 'appear';
echo 'Variables do not $expand $either'; // Outputs: Variables $expand
echo "Variables do not $expand $either"; // Outputs: Variables appear