StringsA string is a series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type.
SyntaxA string literal can be specified in four different ways: Single quoted
The simplest way to specify a string is to enclose it in single
quotes (the character
To specify a literal single quote, escape it with a backslash
(
Double quoted
If the string is enclosed in double-quotes (
As in single quoted strings, escaping any other character will result in the backslash being printed too. The most important feature of double-quoted strings is the fact that variable names will be expanded. See string interpolation for details. Heredoc
A third way to delimit strings is the heredoc syntax:
The closing identifier may be indented by space or tab, in which case the indentation will be stripped from all lines in the doc string. Prior to PHP 7.3.0, the closing identifier must begin in the first column of the line. Also, the closing 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. Example #1 Basic Heredoc example as of PHP 7.3.0
Output of the above example in PHP 7.3: a b c a b c If the closing identifier is indented further than any lines of the body, then a ParseError will be thrown: Example #2 Closing identifier must not be indented further than any lines of the body
Output of the above example in PHP 7.3: PHP Parse error: Invalid body indentation level (expecting an indentation level of at least 3) in example.php on line 4 If the closing identifier is indented, tabs can be used as well, however, tabs and spaces must not be intermixed regarding the indentation of the closing identifier and the indentation of the body (up to the closing identifier). In any of these cases, a ParseError will be thrown. These whitespace constraints have been included because mixing tabs and spaces for indentation is harmful to legibility. Example #3 Different indentation for body (spaces) closing identifier
Output of the above example in PHP 7.3: PHP Parse error: Invalid indentation - tabs and spaces cannot be mixed in example.php line 8 The closing identifier for the body string is not required to be followed by a semicolon or newline. For example, the following code is allowed as of PHP 7.3.0: Example #4 Continuing an expression after a closing identifier
Output of the above example in PHP 7.3: array(2) { [0] => string(11) "a b c" [1] => string(5) "d e f" } Warning
If the closing identifier was found at the start of a line, then regardless of whether it was a part of another word, it may be considered as the closing identifier and causes a ParseError. Example #5 Closing identifier in body of the string tends to cause ParseError
Output of the above example in PHP 7.3: PHP Parse error: syntax error, unexpected identifier "ING", expecting "]" in example.php on line 6 To avoid this problem, it is safe to follow the simple rule: do not choose as a closing identifier if it appears in the body of the text. Warning
Prior to PHP 7.3.0, it is very important to note that the line with the
closing identifier must contain no other characters, except a semicolon
( If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line. Example #6 Invalid example, prior to PHP 7.3.0
Example #7 Valid example, even prior to PHP 7.3.0
Heredocs containing variables can not be used for initializing class properties. Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings. Example #8 Heredoc string quoting example
The above example will output: My name is "MyName". I am printing some Foo. Now, I am printing some Bar2. This should print a capital 'A': A It is also possible to use the Heredoc syntax to pass data to function arguments: Example #9 Heredoc in arguments example
It's possible to initialize static variables and class properties/constants using the Heredoc syntax: Example #10 Using Heredoc to initialize static values
The opening Heredoc identifier may optionally be enclosed in double quotes: Example #11 Using double quotes in Heredoc
Nowdoc
Nowdocs are to single-quoted strings what heredocs are to double-quoted
strings. A nowdoc is specified similarly to a heredoc, but no
String interpolation 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
A nowdoc is identified with the same Example #12 Nowdoc string quoting example
The above example will output: Example of string spanning multiple lines using nowdoc syntax. Backslashes are always treated literally, e.g. \\ and \'. Example #13 Nowdoc string quoting example with variables
The above example will output: My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital 'A': \x41 Example #14 Static data example
String interpolationWhen a string is specified in double quotes or with heredoc, variables can be substituted within it. There are two types of syntax: a basic one and an advanced one. The basic syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort. Basic syntax
If a dollar sign (
The above example will output: He drank some apple juice. Formally, the structure for the basic variable substitution syntax is as follows: string-variable:: variable-name (offset-or-property)? | ${ expression } offset-or-property:: offset-in-string | property-in-string offset-in-string:: [ name ] | [ variable-name ] | [ integer-literal ] property-in-string:: -> name variable-name:: $ name name:: [a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]* Warning
The
Output of the above example in PHP 8.2: Deprecated: Using ${var} in strings is deprecated, use {$var} instead in file on line 6 Deprecated: Using ${expr} (variable variables) in strings is deprecated, use {${expr}} instead in file on line 9 string(3) "foo" string(3) "bar" The above example will output: string(3) "foo" string(3) "bar"
Example #15 Interpolating the value of the first dimension of an array or property
The above example will output: He drank some apple juice. He drank some orange juice. He drank some purple juice. Object value: string.
As of PHP 7.1.0 also negative numeric indices are supported. Example #16 Negative numeric indices
The above example will output: The character at index -2 is n. Changing the character at index -3 to o gives strong. For anything more complex, the advanced syntax must be used. Advanced (curly) syntaxThe advanced syntax permits the interpolation of variables with arbitrary accessors.
Any scalar variable, array element or object property
(static or not) with a
string representation can be included via this syntax.
The expression is written the same way as it would appear outside the
string, and then wrapped in
String access and modification by characterCharacters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr and substr_replace can be used when you want to extract or replace more than 1 character.
Warning
Writing to an out of range offset pads the string with spaces.
Non-integer types are converted to integer.
Illegal offset type emits Warning
Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.
Example #17 Some string examples
String offsets have to either be integers or integer-like strings, otherwise a warning will be thrown. Example #18 Example of Illegal String Offsets
The above example will output: string(1) "b" bool(true) Warning: Illegal string offset '1.0' in /tmp/t.php on line 7 string(1) "b" bool(false) Warning: Illegal string offset 'x' in /tmp/t.php on line 9 string(1) "a" bool(false) string(1) "b" bool(false)
Useful functions and operatorsStrings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String operators for more information. There are a number of useful functions for string manipulation. See the string functions section for general functions, and the Perl-compatible regular expression functions for advanced find & replace functionality. There are also functions for URL strings, and functions to encrypt/decrypt strings (Sodium and Hash). Finally, see also the character type functions. Converting to string
A value can be converted to a string using the
A bool
An int or float is converted to a
string representing the number textually (including the
exponent part for floats). Floating point numbers can be
converted using exponential notation (
Arrays are always converted to the string
In order to convert objects to string, the magic method __toString must be used.
Resources are always converted to strings with the
structure
As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r and var_dump for more effective means of inspecting the contents of these types. Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize function. Details of the String Type
The string in PHP is implemented as an array of bytes and an
integer indicating the length of the buffer. It has no information about how
those bytes translate to characters, leaving that task to the programmer.
There are no limitations on the values the string can be composed of; in
particular, bytes with value This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings.
Given that PHP does not dictate a specific encoding for strings, one might
wonder how string literals are encoded. For instance, is the string
Of course, in order to be useful, functions that operate on text may have to make some assumptions about how the string is encoded. Unfortunately, there is much variation on this matter throughout PHP’s functions:
Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the intl and mbstring extensions. However, using functions that can handle Unicode encodings is just the beginning. No matter the functions the language provides, it is essential to know the Unicode specification. For instance, a program that assumes there is only uppercase and lowercase is making a wrong assumption. |