Most of what a PHP website handles is text. Names and emails arrive from forms, product descriptions come from a database, and everything ends up as HTML sent to a browser. Cleaning, checking, shortening and formatting that text is a daily job for PHP developers.
PHP has a huge library of built-in string functions, more than almost any other language. You've already joined strings with . and put variables inside double quotes in the variables lesson. In this lesson you'll learn the functions you'll actually use most: measuring and changing text, searching and replacing, trimming spaces, splitting text into arrays and joining it back, and formatting numbers and prices neatly.
You'll also learn why a word like "café" can have a surprising length in PHP, and the simple mb_ functions that handle accented letters and other languages correctly.
Length, case and trimming
| Function | Does | Example | Result |
|---|---|---|---|
strlen($s) | Length in bytes | strlen("hello") | 5 |
strtoupper($s) / strtolower($s) | Change case | strtoupper("php") | PHP |
ucfirst($s) | Capitalise the first letter | ucfirst("london") | London |
ucwords($s) | Capitalise every word | ucwords("ada lovelace") | Ada Lovelace |
trim($s) | Remove spaces at both ends | trim(" hi ") | hi |
str_repeat($s, n) | Repeat | str_repeat("-", 5) | ----- |
ltrim and rtrim remove spaces from only one side. Always trim() form input before checking or saving it: a name of three spaces isn't really a name.
Searching and replacing
str_contains($text, "php")returns true or false (PHP 8 and later).str_starts_with()andstr_ends_with()check the beginning or end, such asstr_ends_with($file, ".pdf").strpos($text, "php")gives the position of the first match, counting from 0, orfalseif it's missing.str_replace("cat", "dog", $text)replaces every match. It also accepts arrays, to replace several words at once.str_ireplace()andstripos()do the same while ignoring capital letters.
Be careful with strpos: a match at position 0 is a valid result, so always compare with === false, never with == false.
Parts of strings: substr, explode and implode
substr($s, start, length) takes part of a string: substr("Codevra", 0, 4) gives Code. A negative start counts from the end, so substr($file, -3) gives the last three characters.
explode(",", "red,green,blue") splits a string into an array, and implode(", ", $array) joins an array back into one string. Together they handle comma-separated values, tags, keywords and lists typed by users. To split on several possible separators, such as commas or spaces, you'll use preg_split from the regular expressions lesson.
Formatting with sprintf and number_format
sprintf builds a string from a template with placeholders, and printf prints it directly:
$line = sprintf("%s ordered %d items for £%.2f", "Sam", 3, 24.5);
// Sam ordered 3 items for £24.50%s is a string, %d a whole number and %.2f a number with 2 decimals. %05d pads with zeros, and %-10s left-aligns in 10 characters.
number_format(1234567.891, 2) gives 1,234,567.89, the usual way to show prices and big numbers. str_pad("7", 3, "0", STR_PAD_LEFT) gives 007.
Heredoc and nowdoc for longer text
For several lines of text, such as an email body or an HTML snippet, PHP has heredoc syntax. It starts with <<< and a label, and ends with the same label on its own line:
$name = "Sam";
$count = 3;
echo <<<TXT
Hello $name,
You have {$count} new messages.
TXT;Heredoc interpolates variables like a double-quoted string, but you don't need to escape quotes inside it. The indentation of the closing label is removed from every line, so the output starts at Hello without leading spaces.
Nowdoc is the single-quoted version: write the label in quotes, <<<'RAW', and nothing inside is interpolated, so $price stays as literal text. It's handy for code samples and templates that contain dollar signs.
PHP Strings Syntax
String functions
strlen($s) mb_strlen($s) trim($s)
strtoupper($s) strtolower($s) ucfirst($s) ucwords($s)
str_contains($s, "x") str_starts_with($s, "x") strpos($s, "x")
str_replace("old", "new", $s)
substr($s, 0, 10)
explode(",", $s) implode(", ", $arr)
sprintf("%s: %.2f", $name, $price)
number_format($n, 2) str_pad($s, 5, "0", STR_PAD_LEFT)PHP Strings Summary
- strlen, strtoupper, ucfirst, ucwords and trim measure and tidy text.
- str_contains, str_starts_with and strpos search; check strpos with
=== false. - str_replace replaces text; substr takes part of a string.
- explode splits a string into an array and implode joins an array into a string.
- sprintf and number_format format values; use mb_ functions for UTF-8 text.
PHP Strings Examples
Each example shows the code, the output it produces and what each part does.
Tidying form input
<?php
$name = " ada LOVELACE ";
$email = " Ada@Example.COM ";
$city = "new york";
$name = ucwords(strtolower(trim($name)));
$email = strtolower(trim($email));
$city = ucwords($city);
echo "Name: $name\n";
echo "Email: $email\n";
echo "City: $city\n";
echo "Name length: " . strlen($name) . "\n";
echo str_contains($email, "@example.com") ? "Company email\n" : "Personal email\n";Name: Ada Lovelace
Email: ada@example.com
City: New York
Name length: 12
Company emailLine-by-line explanation
- Line 6Functions work from the inside out: trim the spaces, lower-case everything, then capitalise each word.
- Line 7Emails are stored in lower case so "Ada@Example.COM" and "ada@example.com" match.
- Line 13strlen counts the characters of "Ada Lovelace", including the space.
- Line 14str_contains returns true or false, perfect for a ternary.
Tags, previews and file names
<?php
$input = "php, web, tutorial ,beginner";
$tags = array_map('trim', explode(",", $input));
echo "Tags: " . implode(" | ", $tags) . "\n";
$text = "PHP powers a huge share of the web, from blogs to online shops.";
$preview = strlen($text) > 30 ? substr($text, 0, 30) . "..." : $text;
echo $preview . "\n";
$file = "report-2024.PDF";
$isPdf = str_ends_with(strtolower($file), ".pdf");
echo $isPdf ? "PDF file\n" : "Other file\n";
echo "Position of 2024: " . strpos($file, "2024") . "\n";Tags: php | web | tutorial | beginner
PHP powers a huge share of the...
PDF file
Position of 2024: 7Line-by-line explanation
- Line 3explode splits on commas, and array_map runs trim on every piece.
- Line 4implode joins the clean tags with a new separator.
- Line 7Only shorten text that's longer than 30 characters.
- Line 11Lower-case first, so ".PDF" and ".pdf" both count.
- Line 13"report-" is 7 characters, so 2024 starts at position 7.
An invoice line with sprintf
<?php
$items = [
["Notebook", 3, 3.5],
["Backpack", 1, 34.99],
["Desk lamp", 2, 24.5],
];
$total = 0;
foreach ($items as [$name, $qty, $price]) {
$line = $qty * $price;
$total += $line;
printf("%-10s x%-3d £%8s\n", $name, $qty, number_format($line, 2));
}
printf("%-15s £%8s\n", "TOTAL", number_format($total, 2));
echo "Invoice " . str_pad("42", 6, "0", STR_PAD_LEFT) . "\n";Notebook x3 £ 10.50
Backpack x1 £ 34.99
Desk lamp x2 £ 49.00
TOTAL £ 94.49
Invoice 000042Line-by-line explanation
- Line 8Array destructuring in foreach gives each item's three values names.
- Line 11%-10s left-aligns the name in 10 characters, %-3d left-aligns the quantity, and %8s right-aligns the formatted price.
- Line 13The total line uses the same widths so the prices line up.
- Line 14str_pad adds zeros on the left until the string is 6 characters long.
Common PHP Strings Mistakes
Checking strpos with ==
if (strpos("php rocks", "php") == false) {
echo "Not found"; // printed, because the position is 0
}if (strpos("php rocks", "php") === false) {
echo "Not found";
}Cutting accented text with substr
echo substr("Crème brûlée", 0, 3); // "Cr" plus half a characterecho mb_substr("Crème brûlée", 0, 3); // "Crè"Rounding prices with round() for display
echo "£" . round(12.5, 2); // £12.5echo "£" . number_format(12.5, 2); // £12.50PHP Strings in Real Projects
Strings in PHP applications
Every form handler trims and validates input, blogs create short previews and URL slugs from titles, shops format prices with number_format, and invoices and emails are built with sprintf. Frameworks such as Laravel add helpers on top, like Str::slug() and Str::limit(), but they're built on the same functions you've learned here.
PHP Strings FAQ
What is the difference between strlen and mb_strlen?
strlen counts bytes, and mb_strlen counts characters. For plain English text they match, but strlen("café") is 5 while mb_strlen("café") is 4, because é uses two bytes in UTF-8. Use the mb_ functions whenever text may contain accented letters, other alphabets or emoji.
How do I check whether a string contains another string?
In PHP 8 and later, use str_contains($haystack, $needle), which returns true or false. It's case-sensitive; for a case-insensitive check, compare lowercase versions with mb_strtolower, or use stripos($haystack, $needle) !== false.
How do I reverse a string in PHP?
strrev("abc") gives "cba", but it reverses bytes, so it breaks accented letters and emoji. For UTF-8 text, split it into characters and join them backwards: implode('', array_reverse(mb_str_split($text))).
How do I convert a string to a number?
Cast it with (int) "42" or (float) "2.5", or use intval() and floatval(). Check the input first with is_numeric() or filter_var($value, FILTER_VALIDATE_INT), because casting quietly turns text such as "abc" into 0 and "12abc" into 12.
Should I use single or double quotes for strings?
Either is fine. Single quotes are literal and slightly simpler for text without variables; double quotes interpolate variables and understand escapes such as \n. Many teams use single quotes by default and double quotes when interpolation makes the code clearer. The speed difference is negligible.
PHP Strings Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code so it removes spaces from both ends of the name.
$name = (" Sam ");
What does this print?
echo strtoupper("php") . strlen("code");
What does this print?
$parts = explode("-", "2024-07-05");
echo $parts[1];
Which line shows 1234.5 as 1,234.50?
Why does strlen("café") return 5?
PHP Strings Quiz
5 questions to check what you learned.
Which function joins array items into one string?
- explode
- implode
- join_array
- concat
What does
substr("Codevra", -3)return?- vra
- Cod
- dev
- Codevr
What does
strposreturn when the text isn't found?- -1
- false
- 0
- null
In
sprintf("%.2f", 3.14159), what is the result?- 3.14159
- 3.1
- 3.14
- 3
Which function should you use to count the characters in user-entered text?
- strlen
- count
- sizeof
- mb_strlen