Gen. partnerAlgotech

Escaping characters in a string in PHP

Escaping is used to write characters that have different meanings in different contexts.

|
November 26, 2019

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.

Loading comments...

Stay in the loop

Subscribe to our newsletter and get the latest cybersecurity news delivered straight to your inbox.

Your data is safe. You can unsubscribe from the newsletter at any time.