Strings
Ein String stellt eine Kette von Zeichen dar indem ein Zeichen
gleichbedeutend mit einem Byte ist. Das bedeutet, es gibt exakt 256 mögliche
Zeichen. Es impliziert zudem, dass PHP keine native Unterstützung von Unicode
bietet. Siehe auch Details des
String-Typs.
Hinweis:
Von PHP 7.0.0 gibt es keine besonderen Beschränkungen bezüglicher der Länge
eines String mehr unter 64-bit-Versionen. Unter 32-bit- und
früheren Versionen kann Eine Zeichenkette (String) bis zu 2GB
(maximal 2147483647 bytes) groß werden.
Syntax
Ein String-Literal kann auf vier unterschiedliche Arten spezifiziert werden:
Einfache Anführungszeichen
Der einfachste Weg einen String zu spezifizieren, ist ihn mit
einfachen Anführungszeichen (das Zeichen '
) zu
umschließen.
Um ein einfaches Anführungszeichen hierin anzugeben, fügen sie einen
Backslash (\
) vor dem Zeichen ein. To specify a literal
backslash, double it (\\
). All other instances of
backslash will be treated as a literal backslash: this means that the other
escape sequences you might be used to, such as \r
or
\n
, will be output literally as specified rather than
having any special meaning.
Hinweis:
Im Gegensatz zu den doppelten
Anführungszeichen- und Heredoc-Notationen
werden Variablen und
Escape-Sequenzen für Sonderzeichen nicht maskiert
(ersetzt) wenn sie in einem mit einfachen Anführungszeichen umschlossenen
String erscheinen.
Doppelte Anführungszeichen
Wenn der String in doppelte Anführungszeichen
("
) eingeschlossen wird, interpretiert PHP zusätzliche
Escape-Sequenzen für Sonderzeichen:
Maskierte Zeichen
Sequenz |
Bedeutung |
\n |
Zeilenumbruch (LF or 0x0A (10) in ASCII) |
\r |
Wagenrücklauf (CR or 0x0D (13) in ASCII) |
\t |
horizontaler Tabulator (HT or 0x09 (9) in ASCII) |
\v |
vertikaler Tabulator (VT or 0x0B (11) in ASCII) (seit PHP 5.2.5) |
\e |
Escape-Zeichen (ESC or 0x1B (27) in ASCII) (seit PHP 5.4.4) |
\f |
Seitenvorschub (FF or 0x0C (12) in ASCII) (seit PHP 5.2.5) |
\\ |
Backslash (Rückstrich) |
\$ |
Dollar-Zeichen |
\" |
doppeltes Anführungszeichen |
\[0-7]{1,3} |
the sequence of characters matching the regular expression is a
character in octal notation, which silently overflows to fit in a byte
(e.g. "\400" === "\000")
|
\x[0-9A-Fa-f]{1,2} |
the sequence of characters matching the regular expression is a
character in hexadecimal notation
|
\u{[0-9A-Fa-f]+} |
the sequence of characters matching the regular expression is a
Unicode codepoint, which will be output to the string as that
codepoint's UTF-8 representation (added in PHP 7.0.0)
|
Wie bei Strings in einfachen Anführungszeichen wird beim
maskieren aller anderen Zeichen der Backslash mit ausgegeben. Vor PHP 5.1.1
wurde der Rückstrich vor \{$var}
nicht ausgegeben.
Das Expandieren von Variablen-Namen ist eine der wichtigsten Besonderheiten
von in doppelten Anführungszeichen angegebenen Strings. Siehe
hierzu String-Parsing
für weitere Details.
Heredoc
Eine dritte Möglichkeit Strings zu begrenzen, stellt die Heredoc-Syntax
dar: <<<
. Nach diesem Operator wird ein
beliebiger Bezeichner angegeben, dann eine neue Zeile. Hiernach folgt der
eigentliche String und abschließend erneut der Bezeichner um
die Auszeichnung abzuschließen.
Der schließende Bezeichner muss in der ersten Spalte
der Zeile beginnen. Zudem muss dieser sich an die selben Namensregeln wie
jede andere Kennung in PHP halten: es darf nur alphanumerische Zeichen und
den Unterstrich enthalten und muss mit einem Buchstaben oder dem Unterstrich
beginnen.
Warnung
Es ist sehr wichtig, dass die Zeile mit dem schließenden Bezeichner keine
anderen Zeichen, außer möglicherweise einem Semikolon
(;
), enthält. Das heißt insbesondere auch, dass der
Bezeichner nicht eingerückt wird und auch keine Leerzeichen oder
Tabulatoren vor oder nach dem Semikolon bestehen. Zudem muss das erste
Zeichen vor dem schließenden Bezeichner eine neue Zeile sein, so wie sie
vom Betriebssystem definiert wird. In UNIX Systemen, auch macOS, ist
dies \n
. Auf den schließenden Bezeichner (möglicherweise
gefolgt von einem Semikolon) muss zudem ebenfalls eine neue Zeile folgen.
Wenn diese Regel gebrochen wird und der schließende Bezeichner nicht valide
ist, wird er nicht als Bezeichner angenommen und PHP wird weiter nach einem
solchen schließenden Bezeichner suchen. Wird kein gültiger schließender
Bezeichner vor dem Dateiende gefunden, gibt PHP einen, auf die letzte Zeile
der Datei zeigenden, Parser-Fehler aus.
Beispiel #1 Ungültiges Beispiel
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
// Identifier must not be indented
?>
Beispiel #2 Gültiges Beispiel
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
?>
Heredocs können nicht für die Initialisierung von Klasseneigenschaften
verwendet werden. Seit PHP 5.3 gilt diese Beschränkung nur noch für
Heredocs, die Variablen enthalten.
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.
Beispiel #3 Heredoc string quoting example
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
My name is "MyName". I am printing some Foo.
Now I am printing some Bar2.
This should print a capital 'A': \x41
It is also possible to use the Heredoc syntax to pass data to function
arguments:
Beispiel #4 Heredoc in arguments example
<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>
As of PHP 5.3.0, it's possible to initialize static variables and class
properties/constants using the Heredoc syntax:
Beispiel #5 Using Heredoc to initialize static values
<?php
// Static variables
function foo()
{
static $bar = <<<LABEL
Nothing in here...
LABEL;
}
// Class properties/constants
class foo
{
const BAR = <<<FOOBAR
Constant example
FOOBAR;
public $baz = <<<FOOBAR
Property example
FOOBAR;
}
?>
Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be
enclosed in double quotes:
Beispiel #6 Using double quotes in Heredoc
<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>
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
<![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.
Beispiel #7 Nowdoc string quoting example
<?php
echo <<<'EOD'
Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \\ and \'.
EOD;
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \\ and \'.
Beispiel #8 Nowdoc string quoting example with variables
<?php
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<'EOT'
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
EOT;
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
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
Beispiel #9 Static data example
<?php
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>
Hinweis:
Nowdoc support was added in PHP 5.3.0.
Variable parsing
When a string is specified in double quotes or with heredoc,
variables are parsed within it.
There are two types of syntax: a
simple one and a
complex one.
The simple 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.
The complex syntax can be recognised by the
curly braces surrounding the expression.
Simple syntax
If a dollar sign ($
) is encountered, the parser will
greedily take as many tokens as possible to form a valid variable name.
Enclose the variable name in curly braces to explicitly specify the end of
the name.
Similarly, an array index or an object property
can be parsed. With array indices, the closing square bracket
(]
) marks the end of the index. The same rules apply to
object properties as to simple variables.
Beispiel #10 Simple syntax example
<?php
$juices = array("apple", "orange", "koolaid1" => "purple");
echo "He drank some $juices[0] juice.".PHP_EOL;
echo "He drank some $juices[1] juice.".PHP_EOL;
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;
class people {
public $john = "John Smith";
public $jane = "Jane Smith";
public $robert = "Robert Paulsen";
public $smith = "Smith";
}
$people = new people();
echo "$people->john drank some $juices[0] juice.".PHP_EOL;
echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths."; // Won't work
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
He drank some apple juice.
He drank some orange juice.
He drank some purple juice.
John Smith drank some apple juice.
John Smith then said hello to Jane Smith.
John Smith's wife greeted Robert Paulsen.
Robert Paulsen greeted the two .
As of PHP 7.1.0 also negative numeric indices are
supported.
Beispiel #11 Negative numeric indices
<?php
$string = 'string';
echo "The character at index -2 is $string[-2].", PHP_EOL;
$string[-3] = 'o';
echo "Changing the character at index -3 to o gives $string.", PHP_EOL;
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
The character at index -2 is n.
Changing the character at index -3 to o gives strong.
For anything more complex, you should use the complex syntax.
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because it
allows for the use of complex expressions.
Any scalar variable, array element or object property with a
string representation can be included via this syntax.
Simply write the expression the same way as it would appear outside the
string, and then wrap it in {
and
}
. Since {
can not be escaped, this
syntax will only be recognised when the $
immediately
follows the {
. Use {\$
to get a
literal {$
. Some examples to make it clear:
It is also possible to access class properties using variables
within strings using this syntax.
Hinweis:
Functions, method calls, static class variables, and class
constants inside {$}
work since PHP
5. However, the value accessed will be interpreted as the name
of a variable in the scope in which the string is defined. Using
single curly braces ({}
) will not work for
accessing the return values of functions or methods or the
values of class constants or static class variables.
String access and modification by character
Characters 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.
Hinweis:
As of PHP 7.1.0, negative string offsets are also supported. These specify
the offset from the end of the string.
Formerly, negative offsets emitted E_NOTICE
for reading
(yielding an empty string) and E_WARNING
for writing
(leaving the string untouched).
Hinweis:
Strings may also be accessed using braces, as in
$str{42}, for the same purpose.
Warnung
Writing to an out of range offset pads the string with spaces.
Non-integer types are converted to integer.
Illegal offset type emits E_WARNING
.
Only the first character of an assigned string is used.
As of PHP 7.1.0, assigning an empty string throws a fatal error. Formerly,
it assigned a NULL byte.
Warnung
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.
Hinweis:
As of PHP 7.1.0, applying the empty index operator on an empty string throws a fatal
error. Formerly, the empty string was silently converted to an array.
Beispiel #12 Some string examples
<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];
// Get the third character of a string
$third = $str[2];
// Get the last character of a string.
$str = 'This is still a test.';
$last = $str[strlen($str)-1];
// Modify the last character of a string
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';
?>
As of PHP 5.4 string offsets have to either be integers or integer-like strings, otherwise a warning
will be thrown. Previously an offset like "foo"
was silently cast to 0
.
Beispiel #13 Differences between PHP 5.3 and PHP 5.4
<?php
$str = 'abc';
var_dump($str['1']);
var_dump(isset($str['1']));
var_dump($str['1.0']);
var_dump(isset($str['1.0']));
var_dump($str['x']);
var_dump(isset($str['x']));
var_dump($str['1x']);
var_dump(isset($str['1x']));
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe mit PHP 5.3:
string(1) "b"
bool(true)
string(1) "b"
bool(true)
string(1) "a"
bool(true)
string(1) "b"
bool(true)
Das oben gezeigte Beispiel erzeugt folgende Ausgabe mit PHP 5.4:
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)
Hinweis:
Accessing variables of other types (not including arrays or objects
implementing the appropriate interfaces) using []
or
{}
silently returns null
.
Hinweis:
PHP 5.5 added support for accessing characters within string literals
using []
or {}
.
Converting to string
A value can be converted to a string using the
(string)
cast or the strval() function.
String conversion is automatically done in the scope of an
expression where a string is needed. This happens when using the
echo or print functions, or when a
variable is compared to a string. The sections on
Types and
Type Juggling will make
the following clearer. See also the settype() function.
A boolean true
value is converted to the string
"1"
. Boolean false
is converted to
""
(the empty string). This allows conversion back and
forth between boolean and string values.
An integer 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 (4.1E+6
).
Hinweis:
The decimal point character is defined in the script's locale (category
LC_NUMERIC). See the setlocale() function.
Arrays are always converted to the string
"Array"
; because of this, echo and
print can not by themselves show the contents of an
array. To view a single element, use a construction such as
echo $arr['foo']
. See below for tips on viewing the entire
contents.
In order to convert objects to string magic
method __toString must be used.
Resources are always converted to strings with the
structure "Resource id #1"
, where 1
is the resource number assigned to the resource by PHP at
runtime. While the exact structure of this string should not be relied on
and is subject to change, it will always be unique for a given resource
within the lifetime of a script being executed (ie a Web request or CLI
process) and won't be reused. To get a resource's type, use
the get_resource_type() function.
null
is always converted to an empty string.
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.
String conversion to numbers
When a string is evaluated in a numeric context, the resulting
value and type are determined as follows.
If the string does not contain any of the characters '.', 'e',
or 'E' and the numeric value fits into integer type limits (as defined by
PHP_INT_MAX
), the string will be evaluated
as an integer. In all other cases it will be evaluated as a
float.
The value is given by the initial portion of the string. If the
string starts with valid numeric data, this will be the value
used. Otherwise, the value will be 0 (zero). Valid numeric data is an
optional sign, followed by one or more digits (optionally containing a
decimal point), followed by an optional exponent. The exponent is an 'e' or
'E' followed by one or more digits.
For more information on this conversion, see the Unix manual page for
strtod(3).
To test any of the examples in this section, cut and paste the examples and
insert the following line to see what's going on:
Do not expect to get the code of one character by converting it to integer,
as is done in C. Use the ord() and
chr() functions to convert between ASCII codes and
characters.
Details des String-Typs
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 0
(“NUL bytes”) are allowed
anywhere in the string (however, a few functions, said in this manual not to
be “binary safe”, may hand off the strings to libraries that ignore data
after a NUL byte.)
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
"á"
equivalent to "\xE1"
(ISO-8859-1),
"\xC3\xA1"
(UTF-8, C form),
"\x61\xCC\x81"
(UTF-8, D form) or any other possible
representation? The answer is that string will be encoded in whatever fashion
it is encoded in the script file. Thus, if the script is written in
ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However,
this does not apply if Zend Multibyte is enabled; in that case, the script
may be written in an arbitrary encoding (which is explicity declared or is
detected) and then converted to a certain internal encoding, which is then
the encoding that will be used for the string literals.
Note that there are some constraints on the encoding of the script (or on the
internal encoding, should Zend Multibyte be enabled) – this almost always
means that this encoding should be a compatible superset of ASCII, such as
UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where
the same byte values can be used in initial and non-initial shift states
may be problematic.
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:
-
Some functions assume that the string is encoded in some (any) single-byte
encoding, but they do not need to interpret those bytes as specific
characters. This is case of, for instance, substr(),
strpos(), strlen() or
strcmp(). Another way to think of these functions is
that operate on memory buffers, i.e., they work with bytes and byte
offsets.
-
Other functions are passed the encoding of the string, possibly they also
assume a default if no such information is given. This is the case of
htmlentities() and the majority of the
functions in the mbstring extension.
-
Others use the current locale (see setlocale()), but
operate byte-by-byte. This is the case of strcasecmp(),
strtoupper() and ucfirst().
This means they can be used only with single-byte encodings, as long as
the encoding is matched by the locale. For instance
strtoupper("á")
may return "Á"
if the
locale is correctly set and á
is encoded with a single
byte. If it is encoded in UTF-8, the correct result will not be returned
and the resulting string may or may not be returned corrupted, depending
on the current locale.
-
Finally, they may just assume the string is using a specific encoding,
usually UTF-8. This is the case of most functions in the
intl extension and in the
PCRE extension
(in the last case, only when the
u
modifier is used).
Although this is due to their special purpose, the function
utf8_decode() assumes a UTF-8 encoding and the
function utf8_encode() assumes an ISO-8859-1 encoding.
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.