PHP string functions are built-in tools for measuring, searching, changing, splitting, and formatting text. They include functions such as strlen(), strpos(), str_replace(), and substr(); choosing the right one depends on whether you are handling plain text, multibyte Unicode, or content that will be displayed in a particular context.
What counts as a string in PHP?
A PHP string is a sequence of bytes that PHP treats as text. You can create one with single or double quotes, or with heredoc and nowdoc syntax. Single-quoted strings generally interpret only an escaped backslash and an escaped single quote, while double-quoted strings also parse variables and escape sequences such as a newline. The concatenation operator is a period, not a plus sign.
<?php
$name = 'Mina';
$message = 'Hello, ' . $name;
$message .= '!';
PHP offers a broad set of global string functions rather than requiring a string object with methods. Most functions return a result instead of changing the original string, so assign the result if you want to keep it. For example, $clean = trim($input); creates a trimmed value while leaving $input unchanged. A few functions, such as strtok(), have stateful behavior, but most everyday operations are easier to reason about as ordinary input-and-result operations.
Measure strings and account for Unicode
strlen() returns the number of bytes in a string, not necessarily the number of characters a person perceives. For plain ASCII text, those counts usually match. In UTF-8, a character outside the ASCII range can occupy multiple bytes, so strlen('é') may return 2 when the character is encoded as a two-byte UTF-8 sequence. Emoji can use still more bytes.
For character-oriented operations on UTF-8 text, use the multibyte string extension, commonly called mbstring. Its functions include mb_strlen(), mb_substr(), mb_strtolower(), and mb_strpos(). Specify the encoding when clarity or portability matters:
<?php
$text = 'café';
$bytes = strlen($text);
$characters = mb_strlen($text, 'UTF-8');
Assuming the source is valid UTF-8, $bytes is 5 and $characters is 4. A user-perceived grapheme can contain multiple Unicode code points, however, so even a Unicode-aware character count may not equal the number of visible symbols. If an application must count displayed characters precisely, investigate grapheme-cluster handling, such as PHP’s grapheme_strlen() from the intl extension.
Do not use substr() to cut arbitrary UTF-8 text at a byte offset: it can split a character and produce invalid text. Use mb_substr() for character-based slicing, or grapheme functions when the user-visible unit matters. Confirm that the required extensions are installed and enabled in the PHP environment where the code runs.
Search for text safely
strpos() finds the first occurrence of a substring and returns its numeric byte offset, or false if it cannot find the substring. A common bug is checking the result as a boolean: a match at the beginning has offset 0, which PHP treats as false. Compare strictly instead.
<?php
$position = strpos('PHP strings', 'PHP');
if ($position !== false) {
echo 'Found at byte ' . $position;
}
For a case-insensitive ASCII-oriented search, use stripos(). For UTF-8 text, the corresponding multibyte search function is mb_strpos(), with an appropriate encoding. Functions such as str_contains(), str_starts_with(), and str_ends_with() provide readable checks for containment and prefixes or suffixes in PHP 8 and later. They return booleans, which avoids the offset-zero mistake when the question is simply whether text occurs.
Searching is not the same as validating. Finding a dot in an email address, for example, does not prove the address is valid. Use validation functions or a carefully chosen regular expression when the requirement is to check a format, and be explicit about the accepted rules.
Replace, trim, and change case
str_replace() replaces matching text and can accept arrays of search terms and replacements. It is case-sensitive; str_ireplace() ignores case for its matching. Neither function treats the search string as a regular expression. If you need pattern matching, use the PCRE functions such as preg_replace(), and account for their pattern syntax and escaping rules.
trim() removes whitespace from the beginning and end of a string. It does not remove spaces between words. Its optional second argument is a character mask, not a regular expression, which can surprise developers who expect a phrase to be removed as a whole. For example, trim($value, 'ab') removes any sequence of the characters “a” and “b” from both ends; it does not remove the exact substring “ab” only.
strtolower() and strtoupper() handle basic case conversion, but they are not complete Unicode case-mapping tools. Use mb_strtolower() or mb_strtoupper() for multibyte text, with the right encoding. Case conversion can depend on language-specific rules, so it is not a substitute for a well-defined policy when comparing names or identifiers across languages.
Extract, split, and join strings
substr() extracts part of a string using byte offsets, with optional negative offsets measured from the end. For UTF-8 text, prefer mb_substr() when offsets should count characters. Both functions return a new string; they do not remove a piece from the original variable.
Use explode() to split a string at a literal delimiter, and implode() to join an array of strings with a separator. These are useful for simple, predictable formats, such as comma-separated tags, but splitting on commas alone is not a full CSV parser: quoted CSV fields can contain commas and require CSV-aware handling.
<?php
$tags = 'php, strings, web';
$parts = explode(',', $tags);
$normalized = array_map('trim', $parts);
$result = implode(' | ', $normalized);
Here, $result becomes php | strings | web. For data with quoting, escaping, or embedded delimiters, use a format-specific parser rather than stacking simple string operations and hoping every edge case is covered.
Format text and build output
For straightforward joining, the period operator is usually clearest. For structured output with placeholders, sprintf() returns a formatted string and printf() prints one. Their format specifiers can control values such as integers, decimal precision, and padding. Use them carefully: the format string and the values must agree, or output may be misleading.
<?php
$item = 'notebook';
$quantity = 3;
$summary = sprintf('%d %s(s)', $quantity, $item);
That example produces 3 notebook(s). Formatting is not escaping: sprintf() does not make a value safe for HTML, SQL, a shell command, or a URL. Security depends on the output context, not on whether the string was assembled neatly.
For larger text templates, keep presentation separate from business logic where practical. Concatenating a few values is fine, but elaborate chains can become difficult to audit. A template system can make the intended structure clearer, provided its escaping behavior is understood and configured appropriately.
Escape for the destination, not in general
Strings are often inserted into HTML, and that is where context-aware escaping matters. For ordinary HTML text or quoted attribute values, htmlspecialchars() converts special HTML characters into entities. A common explicit form is:
<?php
$safe = htmlspecialchars($userInput, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
This is appropriate for many HTML text and attribute contexts. It is not a universal sanitizer for JavaScript, CSS, URLs, or SQL. A value placed inside a JavaScript string or a URL component needs handling suited to that specific context; the safest design is often to avoid constructing executable code from untrusted text.
For database queries, do not try to secure SQL by applying addslashes() or by manually replacing quote characters. Use prepared statements with bound parameters through PDO or the relevant database interface. For JSON output, use a JSON encoder such as json_encode() rather than manually adding quotes and backslashes. Escaping and validation solve different problems: escaping protects a particular output context, while validation checks whether input meets application rules.
Common mistakes and practical choices
Many string bugs come from choosing a function that measures or interprets text differently from the application. Before selecting a function, ask what unit is being counted, what kind of match is intended, and where the result will go. The following distinctions prevent frequent errors:
- Use
strlen()for byte length, but use mbstring or grapheme-aware functions for character-oriented work. - Use strict comparison with
strpos(), because a valid match can occur at offset zero. - Use
str_replace()for literal replacement and a regular-expression function only when pattern rules are needed. - Remember that
trim()acts on the ends of a string, not on internal whitespace. - Escape at the point where text enters a specific output format; do not assume one escape function fits every destination.
Also distinguish empty strings from missing values and null. A function expecting a string may behave differently when given another type, and implicit conversions can hide bugs. Validate types and input at application boundaries, and consult the function documentation for return types and version requirements when building code that must run on multiple PHP releases.
Frequently Asked Questions
What is the most commonly used PHP string function? There is no single function that fits every task. strlen(), strpos(), str_replace(), substr(), and trim() are common starting points, but the right choice depends on whether you need to measure, search, replace, extract, or clean text.
How do I check whether a string contains another string in PHP? In PHP 8 and later, use str_contains($haystack, $needle) when you only need a true-or-false answer. On older versions, use strpos() and test with !== false, not a loose boolean check.
Does strlen count characters or bytes? It counts bytes. For UTF-8 character counts, use mb_strlen() with the correct encoding; for visible grapheme clusters, consider grapheme_strlen() when the intl extension is available.
How can I make a string lowercase in PHP? Use strtolower() for basic ASCII text. For multibyte UTF-8 text, use mb_strtolower() and specify or correctly configure the encoding.
Are PHP string functions safe for user input? Not automatically. Functions that search, replace, or format strings do not make input safe for every use. Use prepared statements for SQL, HTML escaping for HTML output, and context-specific encoding for other destinations.
Choosing a reliable approach
For everyday PHP work, begin with the simplest function that matches the job: literal search, literal replacement, trimming, splitting, or joining. Then verify its behavior with the text your application actually accepts, especially non-ASCII input and empty values. If your application processes international text, treat encoding as an explicit design choice rather than assuming that byte offsets equal characters. Finally, handle output according to its destination. Those habits make PHP string functions predictable and help prevent both subtle text corruption and avoidable security mistakes.
Related
- How to Subtotal Data in Excel and Summarize Groups
- C++ Split String Into Array: Practical Methods
- JavaScript split(): Syntax, Examples, and Common Mistakes
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Counting Unique Values in a List: Formulas and TipsTo count distinct, nonblank values in an Excel list, use =IFERROR(ROWS(UNIQUE(FILTER(A2:A100,A2:A100<>""))),0), replacing A2:A100 with your range. In Microsoft…
- Excel INDIRECT Named Range: How It Works and When to Use ItIn Excel, INDIRECT turns text into a cell or range reference, so you can use it to refer…
- Excel Formula to Check Whether a Cell Matches a ListTo check whether a cell’s value appears in a list, use =COUNTIF($D$2:$D$10,A2)>0, assuming the value to check is…
- SQL String Functions: Four Common ExamplesFour useful SQL string functions are UPPER, LOWER, CONCAT, and a length function such as LENGTH. They change…
- How to Add in Excel Using a Formula with SUM and +To add numbers in Excel, enter a formula in the cell where you want the total. With values…
- Excel Formula Not Updating When Dragging Down? FixesIf an Excel formula does not update when you drag it down, first check that you are dragging…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.