/
Basic knowledge

Escaping characters in a string in PHP

26. 11. 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.

Jan Barášek   Více o autorovi

Autor článku pracuje jako seniorní vývojář a software architekt v Praze. Navrhuje a spravuje velké webové aplikace, které znáte a používáte. Od roku 2009 nabral bohaté zkušenosti, které tímto webem předává dál.

Rád vám pomůžu:

Související články

1.
9.