Escape Characters

Escape characters are used to represent characters that are difficult or impossible to type directly in a string, or to insert special characters within a string. These escape characters are typically represented with a backslash (\) followed by a character or a sequence.


Common Escape Characters in PHP


Here’s a list of commonly used escape sequences in PHP:

Escape Sequence

Description

Example

\'

Single quote

'It\'s cool'

\"

Double quote

"She said, \"Hello!\""

\\

Backslash

"C:\\Program Files"

\n

Newline

"Line 1\nLine 2"

\r

Carriage return

"Hello\rWorld"

\t

Tab (horizontal tab)

"Name\tAge"

\v

Vertical tab

"First\vSecond"

\b

Backspace (non-printing)

"Word\b"

\f

Form feed

"Text\fEnd"

\xXX

Hexadecimal character (XX is a two-digit hex number)

"\x41" (outputs 'A')

\u{XXXX}

Unicode escape (for characters above 255)

"Hello \u{1F600}" (outputs "Hello 😀")

Escape Single and Double Quotes


  • To include quotes inside a string, use escape characters for single or double quotes.



Example
<!DOCTYPE html>
<html>
<body>

<?php

// Using single quote inside a single-quoted string
$string1 = 'It\'s a sunny day!'; // Outputs: It's a sunny day!

// Using double quote inside a double-quoted string
$string2 = "She said, \"Hello!\""; // Outputs: She said, "Hello!"
echo $string1;
echo $string2;

?>

</body>
</html>

Try it yourself

Escape Backslashes



  • To include a literal backslash (\), you need to escape it using \\.
Example
<!DOCTYPE html>
<html>
<body>

<?php
$filePath = "C:\\Program Files\\PHP";
echo $filePath; // Outputs: C:\Program Files\PHP
?>

</body>
</html>

Try it yourself

Newlines and Tabs


You can insert newline characters (\n), carriage return (\r), and tabs (\t) inside strings.

Example
<!DOCTYPE html>
<html>
<body>
<pre>
<?php
$text = "Hello\nWorld!";
echo $text; // Outputs:
// Hello
// World!

$tabbedText = "Name\tAge\nJohn\t25";
echo $tabbedText; // Outputs:
// Name Age
// John 25
?>
</pre>

</body>
</html>

Try it yourself

Unicode Characters & Hexadecimal character


Unicode characters can be represented with \u{XXXX}, where XXXX is the Unicode code point (e.g., \u{1F600} for the smiling face emoji) and hexadecimal character can be represented with \xXX, where XX is the Hexadecimal code point .

Example
<!DOCTYPE html>
<html>
<body>

<?php
$x = "\x48\x65\x6c\x6c\x6f"; // Outputs: Hello
echo $x."<br>";

$emoji = "Hello \u{1F600}"; // Outputs: Hello 😀
echo $emoji;

?>

</body>
</html>

Try it yourself

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.