Escaping characters in a string in PHP
Escaping is used to write characters that have different meanings in different contexts.
Escaping is used to write characters that have different meanings in different contexts.
For example, we want to insert another quotation mark into a string enclosed by quotation marks. How to do it?
There are 2 options:
echo "Levi's jeans"; // Combination of quotation types
echo 'Levi's jeans'; // Escaping with backslash
Escaping is also important to do when outputting variables to an HTML template, where the contents of the string may be in a different context and mean something special.
Therefore, for example, when listing HTML code (which we have in a variable) we need to treat the listing, otherwise the HTML code will execute.
For example:
$message = 'Hi <b>Thomas!</b>';
echo $message; // Wrong!
echo htmlspecialchars($message); // Right :)
The issue of escaping is very complex and I recommend reading the article Escaping - The Definitive Guide by David Grudel.