Home  >  Article  >  Backend Development  >  How to escape HTML characters in PHP?

How to escape HTML characters in PHP?

Guanhui
GuanhuiOriginal
2020-07-23 09:28:063749browse

How to escape HTML characters in PHP?

PHP如何转义HTML字符?

在PHP中可以通过使用“htmlentities()”函数转义HTML字符,该函数的作用是将字符转换为HTML转义字符,使用方法只需将HTML传入该函数,其返回值是转义后的HTML字符。

语法

htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] ) : string

使用示例

<?php
$str = "A &#39;quote&#39; is <b>bold</b>";

// 输出: A &#39;quote&#39; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// 输出: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str, ENT_QUOTES);
?>
<?php
$str = "\x8F!!!";

// 输出空 string
echo htmlentities($str, ENT_QUOTES, "UTF-8");

// 输出 "!!!"
echo htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
?>

推荐教程:《PHP

The above is the detailed content of How to escape HTML characters in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn