The PHP htmlentities is an inbuilt function in PHP. It transforms all existing characters to their corresponding HTML Entities where applicable. In this article, we will discuss the PHP htmlentities Function. Also, we will discuss a few examples of using it.
Note: To convert HTML entities back to characters, use the PHP html_entity_decode Function.
string htmlentities( $string, $flags, $encoding, $double_encode )
The PHP htmlentities Function expects four parameters. However, only one parameter is mandatory and rest three are optional. The description of the parameters is as follows:
- $string: The first parameter specifies the input string to convert.
- $flags: The second parameter specifies how to handle quotes. It is a combination of two or more flags. You can refer to the list of all the available flags on PHP.net.
- $encoding: The third parameter specifies the encoding to use while converting. By default, the function uses the default PHP encoding. You can refer to the supported encoding parameters on PHP.net.
- $double_encode: The fourth parameter specifies whether to encode already existing HTML entities. By default, the function encodes everything. However, on turning off, the function will not encode existing HTML entities.
The PHP htmlentities Function returns the string after encoding and transforming characters into HTML entities. However, it returns an empty string if there is an error if the string contains an invalid code sequence.
Let’s consider a few examples of using the function.
Example 1: Simple Encoding
For instance, consider an example of encoding a simple html string.
<?php $htmlString = '<a href="concatly.com">Concatly\'s Blog</a>'; echo htmlentities($htmlString); ?>
The above script prints the following. Also, notice the single quote is present as it is.
Example 2: Converting Quotes
Also, you can convert single quotes by passing the second parameter as ENT_QUOTES.
<?php $htmlString = "This is a 'quote'"; echo htmlentities($htmlString); echo htmlentities($htmlString, ENT_QUOTES); ?>
In the above example, notice the difference on the single quote on passing ENT_QUOTES flag.
In conclusion, we discussed the PHP htmlentities Function in this article. You can read more about it on the Official PHP Documentation. Additionally, you can learn about more PHP String Functions on Concatly.
Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.