Explain it simply
Explain it simply
A string is a piece of text: a name, an e-mail address, a product title, a whole paragraph. In PHP you write it between quotes, and PHP gives you dozens of ready-made functions to measure it, search inside it, clean it up and join it with other strings.
Here is the catch beginners meet sooner or later. PHP does not store letters, it stores bytes. For plain English one letter equals one byte, so everything seems to match. For Myanmar text one character takes three bytes, so the old byte-counting functions and the multibyte mb_ functions suddenly give different answers, and you have to know which one you want.
Problem → Why → Solution
The problem: six characters measure 18
A sign-up form allows display names of at most 10 characters. A user types the Myanmar word မြန်မာ, which is only six characters, yet the check below rejects it. Worse, a developer who shortens long names with substr() ends up with text that is cut in the middle of a character.
<?php
$name = "မြန်မာ"; // six characters to a reader
$limit = 10;
if (strlen($name) > $limit) {
echo "Name too long: " . strlen($name) . " bytes (limit $limit)" . PHP_EOL;
}
$short = substr($name, 0, 10); // cuts through the middle of a characterWhy does a six-character name measure 18?
strlen() counts bytes, and UTF-8 spends three bytes on every Myanmar character, so six characters become 18 bytes. substr($name, 0, 10) also counts bytes: byte 10 lands inside the fourth character, which leaves an invalid half-character that browsers show as a question mark or a replacement symbol. mb_strlen() and mb_substr() fix both problems because they count characters.
Core concept: bytes underneath, characters on top
A PHP string is an ordered row of bytes. PHP itself does not know which character set those bytes belong to; it just stores them. Almost all modern source files and web pages use UTF-8, where an English letter takes one byte, a Myanmar character takes three bytes and an emoji takes four. That is why strlen('မြန်မာ') prints 18 even though the word has six characters.
The classic functions, strlen(), substr(), strpos(), strtoupper() and str_pad(), work on bytes. They are fast and perfectly fine for ASCII text such as IDs, file names, HTTP headers and e-mail addresses. For text that people read, use the mb_ twins from the mbstring extension: mb_strlen(), mb_substr(), mb_strpos(), mb_strtoupper() and mb_str_split(). They decode UTF-8 first, so they count and cut whole characters instead of single bytes.
| Task | Byte function | Character function |
|---|---|---|
| Length | strlen() | mb_strlen() |
| Cut a piece | substr() | mb_substr() |
| Find a position | strpos() | mb_strpos() |
| Upper case | strtoupper() | mb_strtoupper() |
| Split into pieces | str_split() | mb_str_split() |
Quotes decide what PHP does with the text. Single quotes are literal: 'Hi $name' prints the dollar sign and the word name exactly as typed. Double quotes interpolate variables and understand escapes such as \n and \t, and {$user['city']} lets you embed an array element. The dot operator . joins strings, and .= appends to an existing one.
Every string function returns a new string; none of them edits the variable you pass in. trim($name); on its own line does nothing, so write $name = trim($name);. Positions start at 0, and strpos() returns false when nothing is found but 0 when the match is at the very start, so compare with === false. In PHP 8 prefer str_contains(), str_starts_with() and str_ends_with(), which simply return true or false.
- Text arrives as UTF-8 bytes
- Choose a byte or character function
- The function returns a NEW string
- Store or print that new string
Use the mb_ functions for text people read, and the plain ones for IDs, headers and protocols.
General pattern
<?php
$text = "some text"; // single or double quotes
$bytes = strlen($text); // number of bytes
$chars = mb_strlen($text); // number of characters
$part = mb_substr($text, 0, 4); // first 4 characters
$clean = trim($text); // returns a NEW string
$line = "Hello, {$name}!"; // interpolation in double quotes
$joined = $first . " " . $last; // concatenation with a dotReplace the placeholder names with your own. Functions that start with mb_ count characters; the others count bytes. Every function returns a new value, so assign it or print it.
Example: bytes versus characters
The script measures an English phrase and the Myanmar word မြန်မာ with both families of functions, then cuts the first four characters of the Myanmar word. Watch the Burmese lines: the byte count is three times the character count.
<?php
$english = "Learn PHP";
$burmese = "မြန်မာ";
echo "English bytes: " . strlen($english) . PHP_EOL;
echo "English characters: " . mb_strlen($english) . PHP_EOL;
echo "Burmese bytes: " . strlen($burmese) . PHP_EOL;
echo "Burmese characters: " . mb_strlen($burmese) . PHP_EOL;
echo "First 4 characters: " . mb_substr($burmese, 0, 4) . PHP_EOL;
echo strtoupper($english) . PHP_EOL;Code breakdown
- Line 3
$burmese = "မြန်မာ";The file is saved as UTF-8, so these six characters occupy 18 bytes. Save PHP files that contain Myanmar text as UTF-8 without a BOM.
- Line 5
echo "English bytes: " . strlen($english) . PHP_EOL;strlen() counts bytes. For ASCII text bytes and characters are the same, so this prints 9. PHP_EOL is the line break of the current platform.
- Line 6
echo "English characters: " . mb_strlen($english) . PHP_EOL;mb_strlen() counts characters. English gives 9 again, so the two functions only disagree for non-ASCII text.
- Line 7
echo "Burmese bytes: " . strlen($burmese) . PHP_EOL;Three bytes per character gives 18. A byte count like this is what you want for a storage or network-size limit.
- Line 9
echo "First 4 characters: " . mb_substr($burmese, 0, 4) . PHP_EOL;mb_substr(string, start, length) returns length characters from start. substr() would take only four bytes and slice through a character.
- Line 10
echo strtoupper($english) . PHP_EOL;strtoupper() only changes ASCII letters, so this prints LEARN PHP. For accented text such as café use mb_strtoupper().
English bytes: 9
English characters: 9
Burmese bytes: 18
Burmese characters: 6
First 4 characters: မြန်
LEARN PHPQuotes, interpolation and heredoc
Inside single quotes variables are not replaced and \n is not a newline. Inside double quotes $name is replaced by its value and \n is a line break. When letters follow a variable, wrap it as {$name}s so PHP knows where the variable ends. The same braces let you embed an array element such as {$user['city']}.
<?php
$name = "Aye";
$user = ["city" => "Yangon"];
echo 'Hi $name\n' . PHP_EOL; // single quotes: printed exactly as typed
echo "Hi $name\n"; // double quotes: variable plus a newline
echo "City: {$user['city']}" . PHP_EOL;
echo "Plural: {$name}s" . PHP_EOL; // braces mark where the name ends
$greeting = "Hello";
$greeting .= ", " . $name; // .= appends to the existing string
echo $greeting . PHP_EOL;
echo <<<TEXT
Dear {$name},
welcome to {$user['city']}.
TEXT;
echo PHP_EOL;The <<<TEXT ... TEXT; form is called a heredoc. It is a double-quoted string that can span many lines, and interpolation works inside it. Writing <<<'TEXT' with quotes makes a nowdoc, which behaves like single quotes and stays literal. Both are handy for e-mail bodies, long SQL and chunks of HTML.
Search, split, join and format
These are the string functions you will reach for every day. str_contains() and str_starts_with() are case-sensitive, so str_starts_with('Learn PHP', 'php') is false; lower-case both sides first when case should not matter.
| Function | What it does |
|---|---|
| str_contains($text, $needle) | true if the needle appears anywhere |
| str_starts_with() / str_ends_with() | true if the text begins or ends with it |
| trim() / ltrim() / rtrim() | remove spaces and newlines from the ends |
| explode(',', $text) | split a string into an array |
| implode(', ', $items) | join an array into one string |
| sprintf('%.2f', $n) | build a formatted string |
| number_format($n, 2) | add thousands separators |
<?php
$line = " aye,mya,zaw ";
$names = explode(",", trim($line)); // ["aye", "mya", "zaw"]
echo implode(" | ", array_map("ucfirst", $names)) . PHP_EOL;
var_dump(str_contains("Learn PHP", "PHP"));
var_dump(str_starts_with("Learn PHP", "php"));
echo sprintf("%s paid %d MMK (%.1f%%)", "Aye", 4500, 12.345) . PHP_EOL;
echo number_format(1234567.891, 2) . PHP_EOL;
echo str_pad("7", 3, "0", STR_PAD_LEFT) . PHP_EOL;A character is still not always what a reader sees
The mb_ functions count Unicode code points. A Myanmar syllable is built from several of them, a consonant plus medial signs, vowel signs and the asat, so mb_substr($word, 0, 3) drops the asat of မြန် and yields the broken-looking မြန. If the intl extension is installed, grapheme_strlen() and grapheme_substr() count grapheme clusters, which is better, but this word still gives 4, not the two syllables (မြန် and မာ) a Myanmar reader sees.
<?php
$word = "မြန်မာ";
echo mb_strlen($word) . PHP_EOL; // 6 code points
echo mb_substr($word, 0, 3) . PHP_EOL; // splits a syllable in half
echo grapheme_strlen($word) . PHP_EOL; // needs the intl extension
echo grapheme_substr($word, 0, 2) . PHP_EOL;For length limits an approximate count is usually fine, so counting code points is enough. When you truncate text for display, such as adding an ellipsis in a UI, use the grapheme functions and test with real Myanmar text. Splitting exact syllables is a job for a specialised text-segmentation library.
In real projects
Where this shows up in real projects
Every sign-up, profile and checkout form deals with text. Display-name limits, search boxes, slugs for URLs, e-mail normalisation and invoice labels are all string work. A typical slug helper trims the input, lowercases it with mb_strtolower(), replaces spaces with dashes using str_replace() and finally checks the length with mb_strlen().
Databases care about this distinction as well. A MySQL VARCHAR(50) column in a utf8mb4 table counts characters, not bytes, so your PHP validation should use mb_strlen() to agree with it. When you print user-supplied text into a web page, pass it through htmlspecialchars() first, otherwise a name such as <script> becomes part of your page's HTML. Reading a CSV line with explode() is fine for simple lines, but str_getcsv() or fgetcsv() understands quoted commas and should be preferred for real files.
Common mistakes
Common mistakes
1. Counting characters with strlen()
if (strlen($name) > 10) measures မြန်မာ as 18 bytes and rejects it. Use mb_strlen() whenever the limit is about what a person sees, and keep strlen() for genuine byte limits such as a 255-byte index.
2. Testing strpos() without ===
if (strpos($title, 'PHP')) is false when the match starts at position 0, because 0 is falsy, so a title that begins with PHP looks as if it does not contain it. Use str_contains(), or compare with !== false.
3. Expecting trim() to change the variable
trim($input); on a line of its own throws the cleaned value away. A string function returns a new string, so assign it: $input = trim($input);.
4. Putting a variable inside single quotes
echo 'Hello $name'; prints Hello $name literally and never substitutes the value. Use double quotes for interpolation, or write 'Hello ' . $name.
Best practices
Best practices
- Prefer the mb_ functions for text people read (names, titles, comments) and the plain ones for IDs and protocols.
- Save PHP files as UTF-8 without a BOM, and trim() user input before validating it.
- In PHP 8 use str_contains(), str_starts_with() and str_ends_with() instead of strpos() === false; they read better.
Mini challenge
Mini challenge: tidy display names
Write three small helpers for a profile page: shorten a long title, build initials from a full name, and describe how long a text is in characters and in bytes.
- shorten(string $text, int $max): trim the text, and when it is longer than $max characters keep $max - 1 characters and append "…"
- initials(string $fullName): join the first character of every word in upper case, ignoring extra spaces
- describe(string $text): return "text: N characters, M bytes" built with sprintf
- Use the mb_ functions wherever the answer is about characters
<?php
function shorten(string $text, int $max): string
{
// TODO: trim, compare mb_strlen() with $max, cut with mb_substr()
}
function initials(string $fullName): string
{
// TODO: split on spaces, skip empty pieces, take the first character of each
}
function describe(string $text): string
{
// TODO: return something like "မြန်မာ: 6 characters, 18 bytes"
}
// TODO: call each helper with a sample value and echo the resultExpected: A very long… ACM မြန်မာ: 6 characters, 18 bytes
Show hint
mb_substr($text, 0, $max - 1) leaves room for the ellipsis. explode(" ", ...) returns empty strings for double spaces, so skip them.
Show solution
<?php
function shorten(string $text, int $max): string
{
$text = trim($text);
if (mb_strlen($text) <= $max) {
return $text;
}
return mb_substr($text, 0, $max - 1) . "…";
}
function initials(string $fullName): string
{
$letters = "";
foreach (explode(" ", trim($fullName)) as $word) {
if ($word !== "") {
$letters .= mb_strtoupper(mb_substr($word, 0, 1));
}
}
return $letters;
}
function describe(string $text): string
{
return sprintf("%s: %d characters, %d bytes", $text, mb_strlen($text), strlen($text));
}
echo shorten(" A very long article title ", 12) . PHP_EOL;
echo initials("aye chan maung") . PHP_EOL;
echo describe("မြန်မာ") . PHP_EOL;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A PHP string is a row of bytes; in UTF-8 a Myanmar character takes three, so strlen() counts bytes while mb_strlen() counts characters.
- Use mb_ functions for text people read and the plain functions for IDs and protocols.
- Single quotes are literal, double quotes substitute variables and {$expr}, and . and .= join strings.
- String functions return new strings, so assign the result, and prefer str_contains() over strpos().
PHP Language Reference — PHP Documentation Group