PHP strings are byte sequences with single-quoted, double-quoted, heredoc, and nowdoc literal forms. Unicode-aware text needs explicit encoding APIs, and many search functions require strict handling of false versus position zero.
Reliable string work separates canonical values from presentation, encodes at the final output context, binds database values, bounds large input, and tests bytes, Unicode, protocol controls, and empty results.
| Syntax | Behavior | Use |
|---|---|---|
| 'Hello $name' | Variable is not interpolated | Literal text |
| "Hello {$name}" | Variable is interpolated | Readable short templates |
| 'Hello ' . $name | Values are concatenated | Explicit composition |
<?php
$language = 'PHP';
$lessons = 31;
echo "{$language} course: {$lessons} lessons";
PHP course: 31 lessons
Use trim() at text-input boundaries, str_contains() for a simple substring check, and sprintf() when a format has several values or numeric precision rules.
<?php
$rawName = ' Maya Singh ';
$name = trim($rawName);
$message = sprintf('Welcome, %s. Balance: %.2f', $name, 125.5);
echo $message;
Welcome, Maya Singh. Balance: 125.50
Heredoc behaves like a double-quoted string and supports interpolation. Nowdoc behaves like a single-quoted string and keeps variables literal.
Use either form for readable multiline text, not as a substitute for a proper HTML template system in a large application.
strlen() counts bytes, not human-visible characters. When the mbstring extension is available and character count matters, use mb_strlen($text, "UTF-8").
<?php
$label = 'cafe';
echo mb_strlen($label, 'UTF-8');
4
Escape untrusted text at the point where it enters HTML. ENT_QUOTES protects both quote styles, and an explicit UTF-8 encoding makes the output rule clear.
<?php
$comment = '<strong>Hello</strong>';
echo htmlspecialchars($comment, ENT_QUOTES, 'UTF-8');
<strong>Hello</strong>
The browser displays the tags as text instead of interpreting them as HTML.
A PHP string is a sequence of bytes, not an intrinsic Unicode character sequence. `strlen` counts bytes and bracket offsets address bytes. UTF-8 text can use multiple bytes per character, and a user-perceived grapheme may contain several code points.
Use mbstring functions with an explicit encoding for Unicode-aware length, slicing, case conversion, and search where appropriate. For grapheme-level behavior such as cursor movement or visible-character limits, use suitable internationalization support and test combining marks and emoji.
Choose UTF-8 across HTTP, database connections, storage, templates, and source files where the application supports it. Validate or normalize encoding at external boundaries. A string of invalid bytes can corrupt output, logging, JSON, and database operations.
Do not truncate UTF-8 text with byte offsets when the result must remain valid text. Limit transport bytes and visible characters as separate requirements, because a secure upload or database limit may be byte-based while the user limit is grapheme-based.
Single-quoted strings interpret only limited escaping and do not interpolate variables. Double-quoted strings process supported escapes and variable interpolation. Choose the form that makes the intended literal obvious, not a universal style rule that forces excessive escaping.
Use braces around interpolated expressions when a variable boundary or property access could be ambiguous. Avoid embedding complex method calls and conditions inside output strings; compute named values first so escaping and failure are visible.
Heredoc behaves similarly to double-quoted text and supports interpolation, while nowdoc behaves like a single-quoted string. They help with multiline fixtures or templates, but indentation, closing identifiers, and trailing newlines must match supported PHP syntax.
String interpolation is not output encoding and does not make SQL, HTML, JSON, shell, or header contexts safe. Build structured output with the correct API and encode at the final destination boundary.
PHP string search functions differ in return contracts. Functions such as `strpos` may return position zero or false, so compare strictly with `!== false`. A truthy check incorrectly treats a match at the beginning as no match.
Byte-based substring functions are appropriate for ASCII protocols and binary data when offsets are defined in bytes. Use encoding-aware alternatives for user text. Always define whether an end index, length, or negative offset is expected and test empty input.
Simple replacement functions treat search text literally; regular-expression functions interpret a pattern language. Use the simplest tool that matches the requirement. Escape user-provided literal pattern text before inserting it into a regular expression and bound expensive pattern work.
Replacement can return a valid unchanged string when no match exists, while some operations report counts separately. Do not infer success merely from changed output when the original and replacement can be equal. Check the API result designed for that decision.
Concatenation uses the dot operator. Parenthesize when combining concatenation with arithmetic or conditional expressions, especially in code migrated from older PHP precedence rules. Build long structured output with templates or arrays rather than repeated concatenation in nested loops.
`sprintf` and related functions format values under a format string. Keep untrusted data out of the format string itself and pass it as arguments. Match placeholders to value types, locale expectations, precision requirements, and signs; display formatting is not a storage representation.
Casting values to string invokes type-specific rules and may call `__toString` on objects. Arrays do not become useful serialized text through a cast. Use JSON, a delimiter format, or a domain formatter with an explicit schema and error policy.
Use number and date formatters for human-facing locale output. Do not parse localized display strings back into domain values without a locale-aware parser and clear ambiguity policy. Store canonical values separately from presentation.
For HTML text and quoted attribute values, encode untrusted strings with `htmlspecialchars` using an explicit UTF-8 character set and suitable flags. URL components, JavaScript, CSS, CSV, email headers, and shell arguments require different APIs and policies.
Do not pre-escape a value before storage. Store the validated canonical value and encode each time it enters an output context. Pre-escaped data becomes double-encoded in one view and unsafe in another.
Header values must reject carriage return and line feed injection and follow the header grammar. File names need a safe content-disposition strategy, and redirects should use validated destinations. A value safe in page text is not automatically safe in a header.
Use parameterized database queries instead of quoting strings manually. Database escaping depends on connection and driver details and still does not authorize query structure. Map dynamic identifiers through fixed application choices.
Test empty text, position zero, multibyte characters, combining marks, emoji, invalid UTF-8, embedded null bytes where relevant, very long input, line endings, and delimiter collisions. Assert byte and text lengths separately when both limits exist.
Repeated concatenation is often acceptable, but large transformations may be clearer through arrays and `implode`, streams, or incremental response writing. Measure memory and latency with representative payloads before changing readable code.
Avoid copying huge strings repeatedly through nested slicing or replacement. Stream large files and responses under size limits, preserve cancellation or client-disconnect policy, and do not load an untrusted body into memory without a maximum.
Static analysis can identify impossible casts, nullable string use, and unchecked false returns. Runtime tests remain essential for encodings, locale, platform line endings, and extension availability. Declare required extensions in deployment checks without adding a package manager dependency.
Benchmark with realistic encodings and payload distributions; tiny ASCII fixtures can hide the cost and correctness limits of production text.
0 of 2 checked
Try this next
0 of 2 completed
Explore 500+ free tutorials across 20+ languages and frameworks.