Tutorialsplane

PHP htmlspecialchars Function


PHP htmlspecialchars Function : It converts Special Characters to HTML entities. This function returns the converted result as string. This function has its own significance and used frequently. The opposite of this functions is htmlspecialchars_decode(). We are going to explain this example with example and demo.

Let us understand the htmlspecialchars with very basic example – We have some raw data like this – <b>Hi it’s me John</b> now what would happen when user see form data on browser it will show something bold string like this – Hi it’s me John which is wrong because it should show output like this – <b>Hi it’s me John</b> . Now to fix this problem convert HTML tags to its equivalent entities. This is done by using the function htmlspecialchars().


PHP htmlspecialchars Function Syntax

It Converts the following HTML Characters only –

Here is syntax for the function htmlspecialchars

Syntax

htmlspecialchars(string,flags,char-set,double_encode)

Input Parameters

Here are following flags available-

Return Values

This function returns the encodeed string.

Php Version

Supports in php 4+

PHP htmlspecialchars function example

PHP htmlspecialchars function example with single quotes

$string = "<b>Hi it's me John</b>";
echo htmlspecialchars($string);

Try it »

Above Example will produce following output-

HTML Output

Browser Output

PHP htmlspecialchars function example

PHP htmlspecialchars function example with double quotes

$string = '<b>"Hello World"</b>';
echo htmlspecialchars($string);

Try it »

HTML Output

Browser Output

Note : Using htmlspecialchars is good practice. Use this when working with data output or working with characters and entities.

More About htmlspecialchars Funtion

Let’s have some more information about this function.


PHP htmlspecialchars vs htmlentities

The difference between htmlspecialchars and entities is given below-

Read full documentations about htmlentities with example and demo – htmlentities

Tip : Use both the functions where they are needed because both have different efficiency.

PHP htmlspecialchars reverse

If want to perform reverse operation of htmlspecialchars use – htmlspecialchars_decode.

Try Video Demo – All In One Video for this method –

PHP htmlspcialchars function Video Demo –

PHP String Functions