PHP中特殊HTML元素的转换

PHP项目开发过程中,经常需要对一些特殊字符进行处理,否则这些字符可能无法按输出或输出乱码。下面对HTML标记中的一些常用特殊字符进行转换。
q & 转换为 &
q " 转换为 "
q ' 转换为 '
q < 转换为 &lt;
q > 转换为 &gt;


其中,“&”为HTML元素,“&amp;”为显示的字符串。例如,若想在页面正常输出如下代码:
<a href='http://www.mingrisoft.com'>明日科技</a>
则需要在HTML代码中输入:“&lt; a href=&#039;http://www.mingrisoft.com&#039;&gt;明日科技&lt;/a&gt;”,否则,将不能按原义输出。
PHP提供了下面的函数来自动转换为HTML元素。
1.htmlspecialchars()函数
该函数可以将某些特定的字符转换成在HTML中的显示方式。语法如下:
string htmlspecialchars(string str[,int quote_style[,string charset]]);
2.htmlentities()函数
该函数用于把所有的HTML元素转换为显示字符串。语法如下:
string htmlentities(string str[,int quote_style[,string charset]]);
3.html_entity_decode()函数
该函数用于把显示字符串转化为HTML元素。语法如下:
string html_entity_decode(string str[,int quote_style[,string charset]]);
4.htmlspecialchars_decode()

htmlspecialchars_decode() 函数把预定义的 HTML 实体转换为字符。

猜你喜欢

转载自blog.csdn.net/qq_41467799/article/details/81867014