This tutorial shows how to handle strings in PHP, different output methods, functions and the significance of using each of them. A string can be literally expressed in the following ways in PHP
1. Single Quoted
2. Double Quoted
4. NOWDOC (from ver. PHP 5.3.0)
Different methods used to handle strings are:
The simplest way to specify a string is to enclose it in single quotes (the character '). To specify a single quote in your string you will need to escape it with a back slash (). In single quotes all special Characters are not recognised unless they are escaped with the back slash ().
Single Quotes treats Variables as its face value and does not recognise the special characters unless escaped.
Double quoted string is one of the most common method used to specify a string. It has its own advantages and disadvantages. Double quoted string treat variables by expanding it with its value and it also recognizes all the special characters.
Third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
HEREDOC method can be used whenever you have a lot of HTML to be displayed. It can recognise variables and special characters like the double quoted string.
In the above example EOT can be replaced with any value unless you follow the naming rules. Examples: HMV, ROCK, WEBY
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.
A nowdoc is identified with the same <<< seqeuence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.