PHP htmlentities Function | Characters to HTML Entities

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
  • $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
  • $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.

Return Value

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.

PHP htmlentities Function


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.

	$htmlString = '<a href="">Concatly\'s Blog</a>';
	echo htmlentities($htmlString);


The above script prints the following. Also, notice the single quote is present as it is.

htmlentities example 1

Example 2: Converting Quotes

Also, you can convert single quotes by passing the second parameter as ENT_QUOTES.

	$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.

htmlentities example 2


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.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *