PHP string handling functions are built-in tools for measuring, searching, extracting, replacing, splitting, comparing, and formatting text. Choose the function according to the task: for example, use strlen() for byte length, strpos() to find text, str_replace() to replace it, and htmlspecialchars() to safely display text in HTML.
What a string is in PHP
A PHP string is a sequence of bytes. PHP does not require a string to contain text in a particular character encoding, so strings can hold UTF-8 text, other encoded text, or binary data. This detail matters because many familiar string functions operate on bytes rather than human-perceived characters.
You can create strings with single quotes, double quotes, heredoc, or nowdoc syntax. Double-quoted strings and heredoc can interpolate variables; single-quoted strings and nowdoc generally do not. The concatenation operator is a period, not a plus sign:
$name = 'Mina';
$message = 'Hello, ' . $name . '!';
The result in $message is Hello, Mina!. Concatenation builds a new string value, while many functions return a transformed string rather than changing the original variable. Assign the result when you want to keep it:
$text = ' PHP strings ';
$text = trim($text);
PHP function names are case-insensitive, but using the documented lowercase spelling makes code easier to read. Variable names, by contrast, are case-sensitive.
Measuring and changing capitalization
strlen($text) returns the number of bytes in a string. For plain ASCII text, bytes and characters line up, but they do not necessarily match for UTF-8. For example, an accented letter or many emoji use more than one byte. If the application handles UTF-8 text and needs a character count, use mb_strlen($text, 'UTF-8'), provided the mbstring extension is available.
Capitalization functions include strtolower(), strtoupper(), ucfirst(), and ucwords(). The first two are intended for byte-oriented text and are not reliable for all UTF-8 letters. For multibyte text, use mb_strtolower() or mb_strtoupper() with the appropriate encoding. Changing case is not the same as language-aware title casing: word rules vary by language, and simple functions cannot infer every grammatical convention.
Other useful measurement and cleanup tools include:
str_word_count()counts words using its own rules; it is not a general-purpose linguistic tokenizer.str_repeat($text, $times)repeats a string a specified number of times.str_pad($text, $length, $padding)pads a string to a requested length, useful for simple fixed-width output.trim(),ltrim(), andrtrim()remove specified characters from the beginning, end, or both ends.
A common surprise is that trim($text, 'abc') does not remove the substring abc as a unit. Its second argument is a character mask: any of those listed characters can be removed from either end, repeatedly. Also, trim() does not remove every possible Unicode whitespace character by default.
Finding text and checking prefixes
Use strpos($haystack, $needle) to find the first byte position of a substring. It returns an integer position or false if no match exists. Because position zero is valid, test the result with a strict comparison:
$text = 'PHP is useful';
$position = strpos($text, 'PHP');
if ($position !== false) {
echo 'Found at byte ' . $position;
}
The result is Found at byte 0. A loose test such as if ($position) would incorrectly treat that match as false. stripos() searches without regard to ASCII letter case, while strrpos() and strripos() find the last occurrence. These functions are also byte-oriented, so offsets in multibyte text are byte positions.
PHP 8.0 and later provide clearer checks for simple cases: str_contains($text, $needle), str_starts_with($text, $prefix), and str_ends_with($text, $suffix) return booleans. They are convenient when a position is not needed. For older PHP versions, use a careful strpos() !== false check or a suitable alternative.
Extracting, splitting, and joining strings
substr($text, $offset, $length) extracts part of a string using byte offsets. A negative offset counts from the end. For UTF-8 text that must be sliced by characters, use mb_substr() and specify the encoding where appropriate. If you split text with str_split(), remember that it also works with bytes; mb_str_split() is available in current PHP versions for multibyte-aware splitting.
explode($delimiter, $text) separates a string at each occurrence of a literal delimiter and returns an array. The inverse operation is implode($glue, $pieces), which joins array values into one string:
$csv = 'red,green,blue';
$colors = explode(',', $csv);
$line = implode(' | ', $colors);
Here, $colors contains three elements and $line is red | green | blue. These functions do not parse every data format. Splitting CSV on commas fails when a field contains a quoted comma; use PHP’s CSV functions, such as str_getcsv() for parsing a CSV string, when CSV quoting rules matter.
For patterns rather than a fixed delimiter, use regular-expression functions such as preg_match(), preg_match_all(), and preg_split(). Regular expressions are powerful but more complex: patterns need delimiters, and escaping rules can be easy to get wrong. Prefer explode() when the separator is simply a known literal string.
Replacing text and formatting values
str_replace($search, $replace, $subject) replaces literal text and can accept strings or arrays for searches and replacements. str_ireplace() performs a case-insensitive replacement for common ASCII-oriented use. If the replacement should happen only when a pattern matches, use preg_replace() instead. Each function returns the resulting string; str_replace() can also write the number of replacements to an optional output parameter.
For templates with several placeholders, strtr() can replace keys in a mapping. For values that need formatting, sprintf() builds a string according to a format specification, while printf() sends formatted output directly. For example:
$count = 3;
$label = sprintf('%d items', $count);
The value of $label is 3 items. Format specifiers can control integers, floating-point numbers, padding, and other presentation details. Do not treat formatting as input validation: a formatted value may still need checking for the rules of its intended use.
UTF-8, bytes, and international text
A frequent source of PHP string bugs is assuming every string function counts or slices characters. PHP’s core string operations generally work on bytes, because the string itself does not carry an encoding label. UTF-8 is a common choice for web text, but the application must handle it consistently when reading, storing, transforming, and outputting data.
The mbstring extension supplies multibyte-aware operations such as mb_strlen(), mb_substr(), and case-conversion functions. Check that the extension is enabled on the target server before depending on it. Some applications also use the intl extension for Unicode normalization and locale-sensitive behavior. Normalization can matter when visually identical text is represented by different sequences of code points; it is not automatically performed by ordinary string functions.
Do not use byte length as a user-facing character limit without considering the encoding. A database column, HTTP protocol, or binary file may impose a byte limit, while a form requirement may specify characters. Identify which limit applies, then use the corresponding operation and test with non-ASCII examples.
Escaping and security: use the right function
There is no single universal escaping function. Escaping depends on where data will be used. When placing untrusted text into an HTML text node or a quoted HTML attribute, htmlspecialchars() is a common choice:
$safe = htmlspecialchars($input, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
Use the encoded result when rendering in the matching HTML context. This helps prevent text from being interpreted as markup, but it does not make the value safe for JavaScript, CSS, a URL, or every other context. Those require context-appropriate handling. Keep data as data for as long as possible, and escape it at the output boundary for its destination.
addslashes() is not a general security solution and should not be used to protect SQL queries. Use parameterized queries with the database API, such as PDO prepared statements, so values are bound separately from SQL syntax. Similarly, do not assume that removing angle brackets, trimming input, or running strip_tags() makes arbitrary input safe. Validate according to the application’s requirements and encode for the final output context.
Choosing the right function
Start by identifying whether the task concerns literal text, a pattern, Unicode characters, or output safety. A practical selection guide is:
- Need a byte count or byte position? Use
strlen()orstrpos(). - Need a UTF-8 character count or character-based slice? Use the corresponding
mb_function. - Need to find a literal substring? Use
str_contains()on PHP 8.0 or later, or strictstrpos()checking. - Need to split on a known literal delimiter? Use
explode(); use a parser for structured formats such as quoted CSV. - Need simple literal replacement? Use
str_replace(); usepreg_replace()when a regular-expression pattern is genuinely required. - Need HTML output encoding? Use
htmlspecialchars()for the appropriate HTML context, not SQL escaping or a generic sanitizer.
Choosing the simplest function that matches the input and destination usually makes behavior easier to review. Before relying on edge cases, consult the PHP manual for the exact function signature and the PHP version in use; return values, extensions, and newer convenience functions can differ across environments.
Frequently Asked Questions
What is the most commonly used string function in PHP?
There is no single most useful function for every task. strlen(), strpos(), substr(), str_replace(), explode(), and trim() are common, but the right choice depends on whether you are measuring, searching, extracting, replacing, or cleaning text.
How do I check whether a string contains another string in PHP?
On PHP 8.0 or later, use str_contains($text, $needle). On older versions, use strpos($text, $needle) !== false; the strict comparison correctly handles a match at position zero.
Does strlen() count characters or bytes?strlen() counts bytes. For UTF-8 text where a character count is needed, use mb_strlen($text, 'UTF-8') and ensure the mbstring extension is available.
How can I remove whitespace from both ends of a PHP string?
Use trim($text). It removes a defined set of characters from the ends, not from the middle, and its default set does not cover every Unicode whitespace character.
Should I use addslashes() to secure a string?
No. It is not a general-purpose security function and does not safely prepare SQL. Use parameterized database queries for SQL, and encode values appropriately for their output context, such as HTML.
Related
- SPLIT_PART in Snowflake: Syntax, Examples, and Tips
- Split Sheet Meaning: What It Is and How It Works
- Snowflake SELECT SPLIT Example: Parse Delimited Strings
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Average in Excel: Formula, Examples, and Common FixesTo calculate an average in Excel, use the AVERAGE function: if the numbers are in A1:A10, enter =AVERAGE(A1:A10)…
- Excel Data Validation for a Unique ListYes—but Excel’s Data Validation list does not automatically remove duplicates from its source. In Microsoft 365 for Windows,…
- Excel COUNT Formula Examples: Numbers, Blanks, and TextIn Excel for Microsoft 365, use =COUNT(A2:A20) to count cells containing numbers, including dates and times. For other…
- Excel Round to Nearest Quarter: Formula & StepsTo round a number to the nearest quarter (0.25) in Excel, use the formula =MROUND(A1, 0.25). This rounds…
- Wedding Budget Spreadsheet: Sample, Formulas & SetupA useful wedding budget spreadsheet lists each expense, the amount set aside, the latest estimate, the contracted or…
- Excel LET: Can It Use Multiple Variables?Yes. Excel’s LET function allows multiple named values in one formula: write each name and value as a…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.