Strings in PHP
Strings in PHP
Farrukh Ehsan
Escape Sequence Characters
• Escape sequences are used for escaping a character during the string parsing.
• It is also used for giving special meaning to represent line breaks, tabs, alert and more.
Things you already know !
• 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.
Widely used Escape Sequences in PHP
• \’ – To escape ‘ within single quoted string.
• \” – To escape “ within double quoted string.
• \\ – To escape the backslash.
• \$ – To escape $.
• \n – To add line breaks between string.
• \t – To add tab space.
• \r – For carriage return.
• Control character or mechanism used to reset a device's position to the beginning of a
line of text.
Problem !
• \n and other similar escape sequences are not part of HTML.
• HTML ignores carriage return and linefeed characters, treating them as whitespaces.
• If you want to use display a string formatted with \n you can use nl2br to convert it
Example
Strings in PHP
• PHP string is a sequence of characters i.e., used to store and manipulate text.
• There are 4 ways to specify a string in PHP.
1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)
Single Quoted
• We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way
to specify string in PHP.
• For specifying a literal single quote, escape it with a backslash (\) and to specify a literal
backslash (\) use double backslash (\\).
Single Quote | Important Points
• We can store multiple
• line text
• special characters
• escape sequences
in a single-quoted PHP string.
Single Quote | Example
Double Quoted
• In PHP, we can specify string through enclosing text within double
quote also.
Heredoc
• In Heredoc syntax, an identifier is provided after this heredoc <<< operator, and
immediately a new line is started to write any text. To close the quotation, the string
follows itself and then again that same identifier is provided.
• That closing identifier must begin from the new line without any whitespace or tab.
• Naming Rules For Identifier
• The identifier should follow the naming rule that it must contain only alphanumeric
characters and underscores, and must start with an underscore or a non-digit character.
Heredoc | Example
Newdoc | String
• It is also identified with three less than symbols <<< followed by an identifier. But here
identifier is enclosed in single-quote, e.g. <<<'EXP'. Newdoc follows the same rule as
heredocs.
• The difference between newdoc and heredoc is that - Newdoc is a single-quoted
string whereas heredoc is a double-quoted string.