Using WordPress ‘htmlentities2()’ PHP function

The htmlentities2() WordPress PHP function converts entities in a given text, while preserving already-encoded entities.

Usage

htmlentities2( $myHTML )

Example:

Input:

$myHTML = "Convert & Preserve: 5 > 4 & 4 < 5";
echo htmlentities2($myHTML);

Output:

Convert &amp; Preserve: 5 &gt; 4 & 4 &lt; 5

Parameters

  • $myHTML (string) – The text to be converted.

More information

See WordPress Developer Resources: htmlentities2()

Examples

Basic Usage

Convert special characters to their HTML entities while preserving already-encoded entities.

$myHTML = "Hello & Welcome to the <World>!";
echo htmlentities2($myHTML);

Preserve Existing Encoded Entities

Preserve existing encoded entities while converting other special characters.

$myHTML = "AT&T is short for AT&amp;T";
echo htmlentities2($myHTML);

Encode Special Characters in URLs

Encode special characters in URLs to make them safe for usage.

$url = "https://example.com/?search=space & time";
echo htmlentities2($url);

Encode Characters in Form Inputs

Encode special characters in form input values to prevent HTML injection attacks.

$input_value = '"><script>alert("XSS")</script>';
echo htmlentities2($input_value);

Encode Special Characters in JSON Strings

Encode special characters in JSON strings to prevent issues while parsing the JSON data.

$json_string = '{"message": "Hello & Welcome!"}';
echo htmlentities2($json_string);