What are some alternative methods to htmlentities() that can be used to handle special characters in PHP without increasing the output size significantly?

When dealing with special characters in PHP, the htmlentities() function is commonly used to convert these characters into HTML entities to prevent XSS attacks. However, htmlentities() can significantly increase the output size, which may not be ideal for all situations. One alternative method to htmlentities() is using htmlspecialchars() function, which converts special characters to their HTML entities but only for characters that have special meaning in HTML. This can help reduce the output size compared to htmlentities(). Another option is to use the filter_var() function with the FILTER_SANITIZE_STRING filter, which can sanitize input data by removing or encoding special characters.

// Using htmlspecialchars() function
$encoded_string = htmlspecialchars($input_string, ENT_QUOTES, 'UTF-8');

// Using filter_var() function
$encoded_string = filter_var($input_string, FILTER_SANITIZE_STRING);