问题
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