What are the differences between strip_tags, htmlentities, and htmlspecialchars in PHP for handling HTML code?

When handling HTML code in PHP, it is important to sanitize user input to prevent cross-site scripting attacks. strip_tags removes all HTML tags from a string, htmlentities converts special characters to HTML entities, and htmlspecialchars converts special characters to HTML entities but also prevents XSS attacks by encoding characters that have special meaning in HTML.

// Using strip_tags to remove all HTML tags
$cleaned_input = strip_tags($user_input);

// Using htmlentities to convert special characters to HTML entities
$cleaned_input = htmlentities($user_input);

// Using htmlspecialchars to convert special characters to HTML entities and prevent XSS attacks
$cleaned_input = htmlspecialchars($user_input, ENT_QUOTES);