PHP Strings
Strings are sequences of bytes. PHP gives you single quotes, double quotes, heredocs, and nowdocs — each has its own rules about escapes and interpolation.
Single vs double quotes
PHP
$name = 'Ada';
echo 'Hello, $name'; // Hello, $name — no interpolation
echo "Hello, $name"; // Hello, Ada — variables interpolated
echo "Hello, {$user->name}"; // braces let you reach into objects/arrays
Heredoc & Nowdoc
PHP
$body = <<<HTML
<h1>Hello, {$name}</h1>
<p>Welcome to PHP.</p>
HTML;
$raw = <<<'PLAIN'
$name will NOT be interpolated here.
PLAIN;
Common functions
| Function | Returns |
|---|---|
strlen($s) | Byte length. For Unicode characters use mb_strlen. |
strtoupper / strtolower | Case. |
trim / ltrim / rtrim | Strip whitespace. |
substr($s, $start, $len) | Slice. |
str_replace($a, $b, $s) | Replace. |
str_contains / str_starts_with / str_ends_with (8.0+) | Tests. |
explode($sep, $s) / implode($sep, $arr) | Split / join. |
sprintf('%05d', 42) | Formatted output. |
number_format(1234.5, 2) | Locale-style formatting. |
Encoding
Standard PHP string functions work on bytes — that's fine for ASCII, surprising for UTF-8. For Unicode-aware behaviour use the mb_* family (mb_strlen, mb_substr, mb_strtoupper) and set declare(strict_types=1); + mb_internal_encoding('UTF-8').
Tip: When echoing strings into HTML, use
htmlspecialchars(); into URLs, rawurlencode(); into SQL, parameter binding (never concatenation).Example
Example
<?php
$s = 'Hello, PHP!';
echo strlen($s), PHP_EOL;
echo strtoupper($s), PHP_EOL;
echo str_replace('PHP', 'world', $s), PHP_EOL;
echo substr($s, 0, 5), PHP_EOL;
Try it Yourself »
Exercise
Concatenate two strings with…
'Hello, '
$name
A single character; not +.
Discussion
Loading…