How to convert special characters in php

藏色散人
Release: 2023-03-09 07:22:02
Original
2525 people have browsed it

php转换特殊字符的方法:1、通过htmlspecialchars函数进行转换;2、通过“htmlspecialchars_decode”函数进行转换;3、通过htmlentities函数进行转换等等。

How to convert special characters in php

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

PHP特殊字符转换实体函数汇总

1.htmlspecialchars($string, $flag) (Convert special characters to HTML entities 转换特殊字符为HTML实体)

预定义的字符是:
& (和号)成为 &
" (双引号)成为 "
' (单引号)成为 '
< (小于)成为 <
> (大于)成为 >
Copy after login

$flag 默认为ENT_COMPAT | ENT_HTML401

常量名 描述
ENT_COMPAT 转换双引号,不转换单引号。
ENT_QUOTES 单引号和双引号都转换。
ENT_NOQUOTES 单引号和双引号都不转换。
ENT_HTML401 作为HTML 4.01编码处理。
ENT_XML1 作为XML 1编码处理。
ENT_XHTML 作为XHTML编码处理。
ENT_HTML5 作为HTML 5编码处理。

EXP:

    $str = '"2015竞赛&"';
    echo htmlspecialchars($str); //&quot;2015竞赛&amp;&quot;quot;
Copy after login

2.htmlspecialchars_decode($string, $flag) (与上面相反,将特殊的 HTML 实体转换回普通字符)

EXP

    $str  =  "<p>this -&gt; &quot;</p>\n" ;
    
    echo htmlspecial_decode($str); // this -> "
    
    /*不转换双引号*/
    echo htmlspecial_decode($str, ENT_NOQUOTES); // this -> &quot;
Copy after login

3. htmlentities

`htmlentities($string, $flag)`
这个函数与htmlspecialchars的区别网上教程说是也会转换中文,但是我本地php5.5测试两个效果一样
Copy after login
   $str='<a href="test.html">测试页面</a>'; 
   echo htmlentities($str);
   
   $str='<a href="test.html">测试页面</a>'; 
   echo htmlspecialchars($str);
Copy after login

4. html_entity_decode

是`htmlentities`的反函数
Copy after login

5.nl2br

转换换行符(\n(unix), \r(Mac), \r\n(Win))为`<br>`
Copy after login

【推荐学习:PHP视频教程

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

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!