What are the best practices for escaping characters like double quotes or single quotes in PHP code?

When dealing with strings that contain double quotes or single quotes in PHP, it's important to escape these characters to avoid syntax errors or vulnerabilities like SQL injection. One common way to escape these characters is by using the backslash (\) before the quote. Another approach is to use the PHP functions addslashes() or htmlspecialchars() to properly escape the characters.

// Escaping double quotes using backslash
$string = "This is a string with \"double quotes\"";

// Escaping single quotes using backslash
$string = 'This is a string with \'single quotes\'';

// Using addslashes() function to escape quotes
$string = "This is a string with 'single quotes'";
$escaped_string = addslashes($string);

// Using htmlspecialchars() function to escape quotes
$string = "This is a string with \"double quotes\"";
$escaped_string = htmlspecialchars($string, ENT_QUOTES);