Typen
PHP Manual

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 utf8_encode() und utf8_decode() zur Basis-Unicode Funktionalität.

Hinweis: Eine Zeichenkette (String) kann 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. Um einen Backslash vor einem einfachen Anführungszeichen im String oder am Ende des Strings zu verwenden, verdoppeln sie es (\\). Sollten vor ein beliebiges anderes Zeichen einen Backslash setzen, wird dieser mit ausgegeben.

Hinweis: Im Gegensatz zu den anderen Syntax werden Variablen und Escape-Sequenzen für Sonderzeichen nicht maskiert (ersetzt) wenn sie in einem mit einfachen Anführungszeichen umschlossenen String erscheinen.

<?php
echo 'dies ist ein einfacher String';

echo 
'Sie können auch Zeilenumbrüche
in dieser Art angeben,
dies ist okay so'
;

// Gibt aus: Arnold sagte einst: "I'll be back"
echo 'Arnold sagte einst: "I\'ll be back"';

// Ausgabe: Sie löschten C:\*.*?
echo 'Sie löschten C:\\*.*?';

// Ausgabe: Sie löschten C:\*.*?
echo 'Sie löschten C:\*.*?';

// Ausgabe: Dies erzeugt keinen: \n Zeilenumbruch
echo 'Dies erzeugt keinen: \n a Zeilenumbruch';

// Ausgabe: Variablen werden $ebenfalls $nicht ersetzt
echo 'Variablen werden $ebenfalls $nicht ersetzt';
?>

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) (since PHP 5.2.5)
\f Seitenvorschub (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ Backslash (Rückstrich)
\$ Dollar-Zeichen
\" doppelte Anführungszeichen
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation

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 Varibalen-Namen ist eine der wichtigsten Besonderheiten von in doppelten Anführungszeichen angegebenen Strings. Siehe hierzu string parsing für weitere Details.

Heredoc

Ein dritter Weg 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 alhpanumerische Zeichen und den Unterstrich enthalten und muss mit einem Buchstaben oder dem Unterstrich beginngen.

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 Mac OS X, 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.

Heredocs können nicht zur Initialisierung von Klassen-Eigenschaften benutzt werden. Benutzen Sie stattdessen nowdocs.

Beispiel #1 Ungültiges Beispiel

<?php
class foo {
    public 
$bar = <<<EOT
bar
EOT;
}
?>

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 #2 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

Hinweis:

Heredoc support was added in PHP 4.

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 &lt;![CDATA[ ]]&gt; 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 #3 Nowdoc string quoting example

<?php
$str 
= <<<'EOD'
Example of string
spanning multiple lines
using nowdoc 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 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

Hinweis:

Unlike heredocs, nowdocs can be used in any static data context. The typical example is initializing class members or constants:

Beispiel #4 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 was introduced in PHP 4, and 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.

<?php
$beer 
'Heineken';
echo 
"$beer's taste is great"// works; "'" is an invalid character for variable names
echo "He drank some $beers";   // won't work; 's' is a valid character for variable names
echo "He drank some ${beer}s"// works
echo "He drank some {$beer}s"// works
?>

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.

<?php
// These examples are specific to using arrays inside of strings.
// When outside of a string, always quote array string keys and do not use
// {braces}.

// Show all errors
error_reporting(E_ALL);

$fruits = array('strawberry' => 'red''banana' => 'yellow');

// Works, but note that this works differently outside a string
echo "A banana is $fruits[banana].";

// Works
echo "A banana is {$fruits['banana']}.";

// Works, but PHP looks for a constant named banana first, as described below.
echo "A banana is {$fruits[banana]}.";

// Won't work, use braces.  This results in a parse error.
echo "A banana is $fruits['banana'].";

// Works
echo "A banana is " $fruits['banana'] . ".";

// Works
echo "This square is $square->width meters broad.";

// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";
?>

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.

In fact, any value in the namespace can be included in a string with this syntax. Simply write the expression the same way as it would appeared 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:

<?php
// Show all errors
error_reporting(E_ALL);

$great 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo 
"This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."

// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " $arr['foo'][3];

echo 
"This works too: {$obj->values[3]->name}";

echo 
"This is the value of the var named $name{${$name}}";

echo 
"This is the value of the var named by the return value of getName(): {${getName()}}";

echo 
"This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
?>

Hinweis:

Functions and method calls inside {$} work since PHP 5.

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.

Hinweis: Strings may also be accessed using braces, as in $str{42}, for the same purpose. However, this syntax is deprecated as of PHP 6. Use square brackets instead.

Beispiel #5 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';

?>

Hinweis:

Accessing variables of other types using [] or {} silently returns NULL.

Useful functions and operators

Strings 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 regular expression functions or the Perl-compatible regular expression functions for advanced find & replace functionality.

There are also functions for URL strings, and functions to encrypt/decrypt strings (mcrypt and mhash).

Finally, see also the character type functions.

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.

Objects in PHP 4 are always converted to the string "Object". To print the values of object members for debugging reasons, read the paragraphs below. To get an object's class name, use the get_class() function. As of PHP 5, the __toString method is used when applicable.

Resources are always converted to strings with the structure "Resource id #1", where 1 is the unique number assigned to the resource by PHP at runtime. Do not rely upon this structure; it is subject to change. 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. If the PHP engine was built with WDDX support, PHP values can also be serialized as well-formed XML text.

String conversion to numbers

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will be evaluated as an integer.

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.

<?php
$foo 
"10.5";                // $foo is float (11.5)
$foo "-1.3e3";              // $foo is float (-1299)
$foo "bob-1.3e3";           // $foo is integer (1)
$foo "bob3";                // $foo is integer (1)
$foo "10 Small Pigs";       // $foo is integer (11)
$foo "10.2 Little Piggies"// $foo is float (14.2)
$foo "10.0 pigs " 1;          // $foo is float (11)
$foo "10.0 pigs " 1.0;        // $foo is float (11)     
?>

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:

<?php
echo "\$foo==$foo; type is " gettype ($foo) . "<br />\n";
?>

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.


Typen
PHP Manual