Htmlspecialchars and htmlentities usage in php

Source: Internet
Author: User

In php, htmlspecialchars converts special characters into HTML format, while htmlentities converts all the elements into HTML strings. Next I will briefly introduce them.

Htmlentities usage



$ Str = "John & 'adams '";
Echo htmlentities ($ str, ENT_COMPAT );
Echo"
";
Echo htmlentities ($ str, ENT_QUOTES );
Echo"
";
Echo htmlentities ($ str, ENT_NOQUOTES );
?>

John & 'adams'
John & 'adams'
John & 'adams'

Browser output:
The Code is as follows: Copy code

 

Htmlspecialchars usage

& (And) &
"(Double quotation marks)"
<(Less than) to <
> (Greater than) to>

Example



$ Str = "John & 'adams '";
Echo htmlspecialchars ($ str, ENT_COMPAT );
Echo"
";
Echo htmlspecialchars ($ str, ENT_QUOTES );
Echo"
";
Echo htmlspecialchars ($ str, ENT_NOQUOTES );
?>

The Code is as follows: Copy code

 

Their differences

Both functions convert characters into HTML characters, especially url and code strings. Prevents the Character Mark from being executed by the browser. There is no difference when using Chinese, but htmlentities will format Chinese characters to make Chinese Input garbled

Htmlentities converts all html tags. htmlspecialchars only formats the special symbols & '"<and>.

The Code is as follows: Copy code

$ Str = 'test page ';

Echo 'htmlentities specify GB2312 encoding: '.html entities ($ str, ENT_COMPAT, "GB2312 ").'';

Echo 'htmlentities unspecified encoding: '.html entities ($ str ).'';

$ Str = 'test page ';

Echo htmlspecialchars ($ str ).'';

Effect:

The Code is as follows: Copy code

Htmlentities specify GB2312 encoding: test page

Htmlentities does not specify the encoding: ² â ~~~~~~~~

Test page


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.