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

How to escape HTML characters in PHP?

Guanhui
Release: 2023-03-02 22:28:01
Original
3790 people have browsed it

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
Copy after login

使用示例

<?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);
?>
Copy after login
<?php
$str = "\x8F!!!";

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

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

推荐教程:《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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template