要在 PHP 中输出转义字符串,可以使用反斜杠进行转义。例如,要输出一个包含单引号的字符串,可以使用以下代码:
echo "This is a string with a "single quote" in it.";
输出结果为:
This is a string with a "single quote" in it.
如果要输出一个包含双引号的字符串,也可以使用反斜杠进行转义:
echo "This is a string with a "double quote" in it.";
输出结果为:
This is a string with a "double quote" in it.
如果要在输出的字符串中包含 PHP 代码,可以使用 PHP 的内置函数 htmlspecialchars()
进行转义,以避免 XSS 攻击:
echo "This is a string with some <code><?php echo "PHP code"; ?></code> in it.";
echo "This is a string with some <code>" . htmlspecialchars("<?php echo "PHP code"; ?>") . "</code> in it.";
输出结果为:
This is a string with some <code><?php echo "PHP code"; ?></code> in it.
This is a string with some <code><?php echo "PHP code"; ?></code> in it.