Tutorials Logic, IN info@tutorialslogic.com

PHP Strings: Interpolation, Formatting, Unicode, and Safe Output

PHP String Model

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.

Quotes and Concatenation

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

Format a Course Label

Format a Course Label
<?php
$language = 'PHP';
$lessons = 31;

echo "{$language} course: {$lessons} lessons";
Output
PHP course: 31 lessons

String Functions

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.

Normalize a Display Name

Normalize a Display Name
<?php
$rawName = '  Maya Singh  ';
$name = trim($rawName);
$message = sprintf('Welcome, %s. Balance: %.2f', $name, 125.5);

echo $message;
Output
Welcome, Maya Singh. Balance: 125.50

Heredoc and Nowdoc

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.

Unicode Length

strlen() counts bytes, not human-visible characters. When the mbstring extension is available and character count matters, use mb_strlen($text, "UTF-8").

Count UTF-8 Characters

Count UTF-8 Characters
<?php
$label = 'cafe';
echo mb_strlen($label, 'UTF-8');
Output
4
  • This example requires the mbstring extension.

HTML Output

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.

Escape a Comment

Escape a Comment
<?php
$comment = '<strong>Hello</strong>';
echo htmlspecialchars($comment, ENT_QUOTES, 'UTF-8');
Output
<strong>Hello</strong>

The browser displays the tags as text instead of interpreting them as HTML.

Bytes and Encodings

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.

  • Treat core string offsets and length as byte operations.
  • Use encoding-aware APIs for Unicode text.
  • Keep UTF-8 configuration consistent across boundaries.
  • Separate byte limits from visible-character limits.

Literal Forms and Interpolation

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.

  • Choose literals from interpolation and escaping needs.
  • Keep complex expressions outside interpolated text.
  • Use heredoc and nowdoc with deliberate whitespace.
  • Never confuse interpolation with context safety.

Search, Slice, and Replace

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.

  • Compare position results strictly against false.
  • Match slicing APIs to byte or text semantics.
  • Prefer literal replacement unless pattern syntax is required.
  • Use explicit match counts when change detection matters.

Formatting and Conversion

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.

  • Parenthesize concatenation mixed with other operators.
  • Keep format strings trusted and arguments typed.
  • Serialize structured values through an explicit format.
  • Separate canonical storage from localized display.

Output and Security Contexts

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.

  • Encode at the final context, not before storage.
  • Use separate safety rules for HTML, URLs, headers, and commands.
  • Reject control characters in protocol fields.
  • Bind SQL values instead of hand-quoting strings.

String Tests and Performance

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.

  • Cover position zero and Unicode edge cases.
  • Measure large-string allocation before optimization.
  • Stream bounded large data instead of copying it repeatedly.
  • Verify required encoding extensions at deployment.
Before you move on

Mastery Check

5 checks
  • Choose byte or Unicode-aware operations deliberately.
  • Compare search positions strictly against false.
  • Keep complex logic outside interpolation.
  • Encode for the final HTML, URL, header, or command context.
  • Test empty, multibyte, invalid, and oversized input.

String Context Check

0 of 2 checked

Q1. Which function should protect untrusted text inserted into HTML?

Q2. Why can strlen() surprise you with UTF-8 text?

String Boundary

  • Byte length versus character length

    strlen counts bytes, which differs from character count for multibyte text. Use the mbstring functions when logic is defined in Unicode characters.

Try this next

Format and Escape Text

0 of 2 completed

  1. Use sprintf() to format a product name, quantity, and two-decimal total.
  2. Print a string containing <em> once directly and once through htmlspecialchars().
Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.