How should I echo a PHP string variable that conta

2019-02-21 09:20发布

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?

4条回答
小情绪 Triste *
2楼-- · 2019-02-21 09:50

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

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

查看更多
叛逆
3楼-- · 2019-02-21 09:59

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

查看更多
Lonely孤独者°
4楼-- · 2019-02-21 10:00

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.

查看更多
Animai°情兽
5楼-- · 2019-02-21 10:12

I normally use the following code, see htmlspecialchars

<?php echo htmlspecialchars($videoId, ENT_QUOTES | ENT_HTML5); ?>
查看更多
登录 后发表回答