Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

PHP htmlspecialchars Function: Description, Parameters, Return Value, and Usage Examples

PHP htmlspecialchars Function: Description, Parameters, Return Value, and Usage Examples

This article explains the PHP htmlspecialchars function, detailing its purpose of converting predefined characters to HTML entities, describing each parameter and return value, and providing multiple code examples that demonstrate different flag options and their effects on output.

The htmlspecialchars function converts predefined characters such as <, >, &, " and ' into their corresponding HTML entities, helping to prevent XSS attacks and ensuring proper HTML rendering.

Function signature :

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT|ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] )

Parameters : string $string (required) – the input string to be converted. int $flags (optional) – determines how quotes and invalid code points are handled; common values are ENT_COMPAT, ENT_QUOTES, ENT_NOQUOTES, and document type flags like ENT_HTML401. string $encoding (optional) – character set to use, defaulting to the value of default_charset. bool $double_encode (optional) – if true, existing HTML entities are encoded again; set to false to leave them untouched.

Return value :

The function returns the converted string. If the input contains invalid encoding, an empty string is returned unless ENT_IGNORE or ENT_SUBSTITUTE flags are set.

Example 1 – Different flag options :

<?php
$str = "Bill & 'Steve'";
// Convert only double quotes (default behavior)
echo htmlspecialchars($str, ENT_COMPAT);

// Convert both double and single quotes
echo htmlspecialchars($str, ENT_QUOTES);

// Do not convert any quotes
echo htmlspecialchars($str, ENT_NOQUOTES);
?>

Output of the above code:

Bill & 'Steve'<br>
Bill &amp; 'Steve'<br>
Bill & 'Steve'

Example 2 – Converting quotes inside a string :

<?php
$str = 'I love "PHP".';
echo htmlspecialchars($str, ENT_QUOTES);
?>

Result:

I love &quot;PHP&quot;.
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Report an issue with this article
backendhtmlspecialcharsphp-functionsHTML entities

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion