我应该如何回显包含特殊字符的 PHP 字符串变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17150403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:22:38  来源:igfitidea点击:

How should I echo a PHP string variable that contains special characters?

phpstringspecial-characters

提问by PHP

I'm trying to populate a form with some data that contains special characters (e.g. single quote, double quote,<,>,?,","".~,,!@#$%^&*()_+}{":?<<>,./;'[.] etc) :

我正在尝试使用一些包含特殊字符的数据填充表单(例如单引号、双引号、<、>、?、"、"".~,,!@#$%^&*()_+} {":?<<>,./;'[.] 等):

<input type="text" name="message" size="200" maxlength="200"
 value =<?php echo $message;?>> 

However, $message, which comes from a MySQL table, isn't displayed correctly - any HTML output that should be in $messageis broken.

但是,$message来自 MySQL 表的 没有正确显示 - 任何应该在其中的 HTML 输出$message都已损坏。

How do I do this properly?

我该如何正确执行此操作?

回答by Alexandre Danault

This will prevent your tags from being broken by the echo:

这将防止您的标签被回声破坏:

<?php echo htmlentities($message); ?>

<?php echo htmlentities($message); ?>

回答by Touch

If you want to display it

如果你想显示它

echo htmlspecialchars($messge, ENT_QUOTES, 'UTF-8');

That's what I usually do.

这就是我通常所做的。

Since the answers are difference:

由于答案不同:

htmlentities-vs-htmlspecialcharsis worth checking out.

htmlentities-vs-htmlspecialchars值得一试。

回答by Hugo Delsing

I normally use the following code, see htmlspecialchars

我通常使用以下代码,请参阅htmlspecialchars

<?php echo htmlspecialchars($videoId, ENT_QUOTES | ENT_HTML5); ?>

回答by Degar007

whats wrong with using a constant ?

使用常量有什么问题?

<?php
define(foo,'<,>,?,","".~,,!@#$%^&*()_+}{":?<<>,./;');
$foo2="'[.]";
echo constant('foo').$foo2;
?>

you need to put the '[.]' into a variable, as a constant will break on a '(single quote).

您需要将 '[.]' 放入变量中,因为常量会在'(单引号)上中断。