Chapter 7: Strings and Text Processing
Strings store and manipulate text. PHP offers several literal syntaxes, hundreds of string functions, full Unicode support through mbstring, and regular expression tools for advanced matching. Handling text correctly means choosing the right quoting, encoding, and cleaning strategy for each situation.
Single, Double, heredoc, and nowdoc
PHP provides several syntaxes for string literals. The main differences are how variables are interpreted and how quotes or line breaks are handled.
Using single quotes for literal text
Single-quoted strings treat most characters literally. Escape only the single quote itself and backslashes.
<?php
$name = 'Alice';
echo 'Hello $name'; // prints Hello $name
echo 'It\'s PHP time';
?>
Using double quotes for interpolation
Double-quoted strings allow variable and escape sequence expansion. They are convenient for building messages with embedded values.
<?php
$name = "Alice";
echo "Hello $name"; // prints Hello Alice
echo "Line one\nLine two";
?>
Creating multi-line strings with heredoc
A heredoc starts with <<<LABEL and ends with LABEL; on its own line. It behaves like a double-quoted string.
<?php
$text = <<<HTML
Hello $name,
This is a heredoc example.
HTML;
echo $text;
?>
Creating raw multi-line strings with nowdoc
nowdoc syntax uses single quotes around the label and does not expand variables or escapes.
<?php
$snippet = <<<'CODE'
function hello() {
echo "Hi there";
}
CODE;
echo $snippet;
?>
heredoc for generated text such as HTML or SQL, and nowdoc for raw templates or code examples that should remain untouched.
Interpolation and Escape Sequences
Interpolation replaces variable names in double-quoted or heredoc strings with their values. Escape sequences represent special characters like newlines or tabs.
Embedding variables safely
Simple variables interpolate directly. When concatenating arrays or complex expressions, use braces to make boundaries clear.
<?php
$user = "Maya";
echo "Welcome $user"; // OK
echo "Hello {$user}!"; // clearer
?>
Understanding escape sequences
Common sequences include \n (newline), \t (tab), and \\ (backslash). Only recognized in double-quoted or heredoc strings.
<?php
echo "Path: C:\\Program Files\\PHP";
echo "\nTabbed\tText";
?>
nowdoc strings are not expanded; escaping other sequences has no effect there.
Common String Functions
PHP includes many built-in functions for measuring, searching, and manipulating strings. Most are case-sensitive; some have case-insensitive variants ending in i.
Measuring and slicing strings
When working with text, you often need to know its length or extract a part of it. Functions like strlen() and substr() make this easy, giving you direct access to character counts and specific portions of strings without manually looping through them.
<?php
$str = "Hello World";
echo strlen($str); // 11
echo substr($str, 6, 5); // World
?>
Changing case and trimming
Normalizing text to consistent case and removing unwanted whitespace are common preparation steps before comparison or output. PHP’s case-conversion and trimming functions ensure predictable formatting and cleaner presentation.
<?php
echo strtoupper("php"); // PHP
echo strtolower("PHP"); // php
echo trim(" space "); // space
?>
Searching and replacing text
Locating or replacing text within larger strings is a frequent task in text processing. PHP provides simple search functions and direct replacements that are fast and safe for plain text operations without needing regular expressions.
<?php
$msg = "red, green, blue";
echo strpos($msg, "green"); // 5
echo str_replace("green", "yellow", $msg);
?>
str_contains(), str_starts_with(), and str_ends_with() (PHP 8+) for clean, readable conditionals.
Splitting and joining
Splitting breaks a string into pieces using a delimiter, while joining (or imploding) assembles an array back into a single string. These operations are useful when processing comma-separated data or reconstructing messages from parts.
<?php
$items = explode(",", "a,b,c");
echo implode("-", $items); // a-b-c
?>
Formatting and padding
Formatting inserts values into templates and adjusts output for display. Padding functions ensure consistent width for aligned text or numeric fields, which is especially helpful when building tables or reports.
<?php
printf("Pi is about %.2f", 3.14159);
echo str_pad("42", 5, "0", STR_PAD_LEFT); // 00042
?>
Multibyte Strings with mbstring
PHP strings are sequences of bytes, not characters. Multibyte functions ensure correct handling of UTF-8 and other encodings for languages beyond ASCII.
Measuring multibyte strings
Use mb_strlen() instead of strlen() when working with UTF-8 text. Set the internal encoding first for consistency.
<?php
mb_internal_encoding("UTF-8");
echo mb_strlen("café"); // 4, not 5
?>
Extracting and converting substrings
Multibyte strings require special handling to avoid splitting characters mid-sequence. Functions like mb_substr() and mb_convert_case() work safely on UTF-8 data, allowing accurate slicing and case transformation for all languages.
<?php
$str = "Здравствуйте";
echo mb_substr($str, 0, 5); // first few characters
echo mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
?>
"UTF-8" when calling mb_* functions if your environment defaults may differ.
Regular Expressions with PCRE
Regular expressions find or replace complex text patterns. PHP’s PCRE functions use the Perl-Compatible Regular Expression engine, providing a powerful pattern syntax.
Matching patterns with preg_match()
preg_match() tests for a match and optionally captures groups.
<?php
$email = "user@example.com";
if (preg_match("/^[\w\.-]+@[\w\.-]+\.\w+$/", $email)) {
echo "Valid email";
}
?>
Finding all matches with preg_match_all()
When you need to locate every occurrence of a pattern, preg_match_all() collects them into an array for inspection or further processing. This is useful for tasks like extracting all URLs, numbers, or tags from text.
<?php
$text = "one two three two";
preg_match_all("/two/", $text, $matches);
print_r($matches);
?>
Replacing with preg_replace()
preg_replace() performs regular expression substitutions, allowing dynamic rearrangement of captured groups or conversion of matched patterns. It is the flexible counterpart to simple str_replace() for structured text.
<?php
$sentence = "2025-11-04";
echo preg_replace("/(\d{4})-(\d{2})-(\d{2})/", "$3/$2/$1", $sentence);
?>
u modifier (for Unicode) when processing UTF-8 text, for example /pattern/u.
Testing replacements and captures
Always test patterns on sample data; unexpected greediness or anchoring can cause subtle bugs.
<?php
preg_match("/(a+)(b+)/", "aaabb", $parts);
print_r($parts); // shows groups a and b separately
?>
Filtering and Sanitization
Filtering ensures data is valid; sanitization removes or escapes unsafe characters. PHP’s filter_var() and related functions offer built-in filters for common cases like email and URL validation.
Validating input with filter_var()
Validation confirms that data meets specific rules before use. filter_var() checks input against built-in filters, helping prevent errors or misuse by rejecting malformed values early in your code.
<?php
$email = "user@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
}
?>
Sanitizing text to remove unwanted characters
Sanitization cleans input by stripping or escaping unsafe characters, reducing risks of injection or display errors. PHP’s filters offer simple ways to ensure incoming data stays within safe, predictable bounds.
<?php
$name = "<b>Bob</b>";
echo filter_var($name, FILTER_SANITIZE_STRING);
?>
FILTER_SANITIZE_STRING is deprecated in newer PHP versions. Use htmlspecialchars() or stricter escaping based on your context (HTML, URL, SQL).
Escaping for HTML output
Escaping converts special characters into harmless HTML entities, preventing browsers from interpreting them as code. Always escape user-provided data before embedding it in HTML to avoid cross-site scripting vulnerabilities.
<?php
$userInput = "<script>alert('xss')</script>";
echo htmlspecialchars($userInput, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
?>