Start · Sprachen · PHP · Kapitel · Strings
// Kapitel · PHP

Strings

PHP hat die vielleicht umfassendste String-Bibliothek aller Sprachen. Achte auf UTF-8 und nutze die mb_*-Funktionen.

String-Operationen

$s = 'programmierung.net';

strlen($s);              // 18 (Byte-Länge, nicht Zeichen!)
mb_strlen($s);           // 18 (Zeichen-Länge, UTF-8-sicher)
strtoupper($s);          // 'PROGRAMMIERUNG.NET'
str_replace('.net', '.de', $s);
str_contains($s, 'net'); // true (PHP 8.0+)
str_starts_with($s, 'prog');
str_ends_with($s, '.net');
substr($s, 0, 12);       // 'programmieru'
explode('.', $s);        // ['programmierung', 'net']
implode(', ', $arr);
trim("  hallo  ");       // 'hallo'

Vorsicht: UTF-8

strlen() zählt Bytes, nicht Zeichen. Für internationalen Text immer mb_*-Funktionen nutzen:

$s = 'Größe';
strlen($s);       // 6 (weil ö = 2 Bytes in UTF-8)
mb_strlen($s);    // 5 (korrekt)

Heredoc & Nowdoc

Für mehrzeilige Strings mit oder ohne Variablen-Interpolation:

$name = 'Anna';

// Heredoc — mit Interpolation (wie doppelte Anführungszeichen)
$mail = <<<MAIL
Hallo $name,

willkommen auf programmierung.net.

Gruß
MAIL;

// Nowdoc — OHNE Interpolation (wie einfache Anführungszeichen)
$sql = <<<'SQL'
SELECT * FROM users WHERE email = ?
SQL;

Formatierung mit sprintf

$preis = 19.99;
echo sprintf('%.2f €', $preis);           // 19.99 €
echo sprintf('%05d', 42);                 // 00042
echo sprintf('%s hat %d Punkte', 'Anna', 100);