0
0
PHPprogramming~5 mins

Escape sequences in strings in PHP

Choose your learning style9 modes available
Introduction
Escape sequences let you put special characters inside strings that are hard to type directly, like new lines or tabs.
When you want to add a new line inside a string to make output easier to read.
When you need to include quotes inside a string without ending it early.
When you want to add a tab space inside a string for formatting.
When you want to include a backslash character itself inside a string.
When you want to add special characters like carriage return or alert sounds.
Syntax
PHP
"\n", "\t", "\\", "\"", "\'"
Escape sequences start with a backslash (\) followed by a character.
Use double quotes for strings with escape sequences to work properly in PHP.
Examples
Adds a new line between Hello and World.
PHP
$text = "Hello\nWorld!";
echo $text;
Includes double quotes inside the string.
PHP
$quote = "She said, \"Hi!\"";
echo $quote;
Shows how to include backslashes in a file path.
PHP
$path = "C:\\Program Files\\";
echo $path;
Adds a tab space between two words.
PHP
$tabbed = "Column1\tColumn2";
echo $tabbed;
Sample Program
This program shows different escape sequences: new line, quotes, backslashes, and tab.
PHP
<?php
$text = "Line1\nLine2";
echo $text . "\n";

$quote = "He said, \"Hello!\"";
echo $quote . "\n";

$path = "C:\\Windows\\System32";
echo $path . "\n";

$tab = "Name\tAge";
echo $tab . "\n";
?>
OutputSuccess
Important Notes
Single quoted strings in PHP do not interpret most escape sequences except \' and \\.
Always use double quotes if you want escape sequences like \n or \t to work.
Remember to double backslashes when you want to show a single backslash.
Summary
Escape sequences let you add special characters inside strings.
Use a backslash (\) before a character to escape it.
Double quotes are needed in PHP strings to recognize escape sequences.