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

自古美人都是妖i 提交于 2019-12-01 13:39:23

问题


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 $message is broken.

How do I do this properly?


回答1:


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

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




回答2:


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-htmlspecialchars is worth checking out.




回答3:


I normally use the following code, see htmlspecialchars

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



回答4:


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).



来源:https://stackoverflow.com/questions/17150403/how-should-i-echo-a-php-string-variable-that-contains-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!