Is there an alternative way to write string literals in PHP (without ' or ")? Is there an alternative way to write string literals in PHP (without ' or ")? php php

Is there an alternative way to write string literals in PHP (without ' or ")?


There are 4 ways to encapsulate strings, single quotes ', double quotes ", heredoc and nowdoc.

Read the full php.net article here.

Heredoc

A 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.

http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

$str = <<<EODExample of stringspanning multiple linesusing heredoc syntax.EOD;

Nowdoc

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 construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same <<< sequence 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.

http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

$str = <<<'EOD'Example of stringspanning multiple linesusing nowdoc syntax.EOD;

Escaping

If you want to use literal single or double quotes within single or double quoted strings, you have to escape them:

$str = '\''; // single quote$str = "\""; // double quote

As Herbert noted, you don't have to escape single quotes within a double quoted strings and you don't have to escape double quotes within a single quoted string.


If you have to add quotes on a large scale, use the addslashes() function:

$str = "Is your name O'reilly?";echo addslashes($str); // Is your name O\'reilly?