PHP Escape Sequences

by Vincy. Last modified on July 9th, 2022.

Escape sequences are used for escaping a character during string parsing. It is also used for giving special meaning to represent line breaks, tabs, alerts and more.

The escape sequences are interpolated into strings enclosed by double quotations or heredoc syntax. If a string is within the single quotes or in nowdocs, then the escape sequence will not work to get the expected result. In a previous tutorial, we have seen variable interpolation.

Escape sequences are started with the escaping character backslash (\) followed by the character which may be an alphanumeric or a special character. If it is an alphanumeric character, it gives special meaning to represent the line breaks \n, carriage return \r and more.

If it is a special character, then it will be considered as it is during the string parsing. For example, if we interpolate \$var into a string then it will be taken as $var. Without the escaping character (\), the $var PHP variable is parsed to get its value.

Escape Sequence Example

This code shows a simple PHP example program to distinguish the behavior of the escape sequences with alphanumeric and non-alphanumeric characters.

In this example, I used the escape sequence \n to add a line break after label and I have used \\ to escape \ character and print it to the browser.

echo "PHP Escape Sequences:\n Backslash \\ is used as an escaping character.";

Widely used Escape Sequences in PHP

In this section, I have listed some of the widely used escape sequences and describe how they are used to escape the special character or to give meaning by combining them with some alphanumeric characters.

  • \’ – To escape ‘ within the single-quoted string.
  • \” – To escape “ within the double-quoted string.
  • \\ – To escape the backslash.
  • \$ – To escape $.
  • \n – To add line breaks between strings.
  • \t – To add tab space.
  • \r – For carriage return.
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “PHP Escape Sequences”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page