PHPCommon String Functions

Common String Functions

PHP ships with a huge library of built-in string functions — a legacy of its origins as a text-processing and web-templating language. Rather than memorize the whole list, it's more useful to learn a handful of workhorse functions that cover almost every task: measuring, trimming, searching, replacing, slicing, splitting, and padding. This page walks through those, with runnable examples for each, plus a quick-reference table at the end.

strlen(): measuring byte length

strlen() returns the number of bytes in a string. It's the function you reach for first when validating input length, though it counts bytes rather than "characters" — a distinction that only matters once multibyte UTF-8 text enters the picture (covered on the multibyte strings page).

strlen-example.php

PHP
<?php

$password = 'letmein123';

if (strlen($password) < 8) {
    echo 'Too short';
} else {
    echo 'Length OK: ' . strlen($password);
}
Length OK: 10
strtolower() and strtoupper(): case conversion

These two do exactly what they say, operating on ASCII letters by default. They're commonly used to normalize user input before comparison — for example, matching an email address regardless of how the visitor capitalized it.

case-conversion.php

PHP
<?php

$input = 'User@Example.COM';

echo strtolower($input);
echo PHP_EOL;
echo strtoupper('shout this');
user@example.com
SHOUT THIS
trim(), ltrim(), rtrim(): stripping whitespace

trim() removes whitespace (or a custom set of characters) from both ends of a string; ltrim() and rtrim() restrict that to the left or right side only. All three are essential when handling form input, since users routinely paste text with stray leading or trailing spaces and newlines.

trim-example.php

PHP
<?php

$raw = "  hello world  \n";

echo '[' . trim($raw) . ']';
echo PHP_EOL;
echo '[' . ltrim($raw) . ']';
echo PHP_EOL;
echo '[' . rtrim($raw) . ']';
echo PHP_EOL;

// Custom character set: strip slashes, not spaces
echo trim('/api/users/', '/');
[hello world]
[hello world  
]
[  hello world]
api/users
str_replace(): swapping substrings

str_replace($search, $replace, $subject) replaces every occurrence of $search with $replace inside $subject. All three arguments can be arrays, which lets you perform several replacements in a single call.

str-replace-example.php

PHP
<?php

$template = 'Hello {name}, your order {order} has shipped.';

$result = str_replace(
    ['{name}', '{order}'],
    ['Priya', '#4821'],
    $template
);

echo $result;
Hello Priya, your order #4821 has shipped.
substr(): extracting part of a string

substr($string, $start, $length) returns a slice of the string. $start can be negative to count from the end, and omitting $length returns everything from $start to the end of the string.

substr-example.php

PHP
<?php

$sku = 'PROD-2024-SHIRT-M';

echo substr($sku, 0, 4);   // PROD
echo PHP_EOL;
echo substr($sku, 5, 4);   // 2024
echo PHP_EOL;
echo substr($sku, -1);     // M — last character
PROD
2024
M
strpos() and str_contains(): searching inside a string

strpos($haystack, $needle) returns the byte offset of the first occurrence of $needle, or false if it isn't found. That false return is a classic gotcha: offset 0 (found at the very start) and false (not found) are both "falsy" in a loose comparison, so code must use the strict !== operator to tell them apart. PHP 8 added str_contains(), which sidesteps the whole problem by returning a plain boolean.

strpos-vs-str-contains.php

PHP
<?php

$text = 'The quick brown fox';

$pos = strpos($text, 'quick');
if ($pos !== false) {
    echo "Found at offset $pos" . PHP_EOL;
}

// PHP 8+: no offset arithmetic needed, no false/0 confusion
if (str_contains($text, 'fox')) {
    echo 'Contains fox';
}
Found at offset 4
Contains fox
The classic strpos() pitfall
`if (strpos($text, 'The')) { ... }` looks correct but silently fails when the needle is at offset `0`, because `0` evaluates to `false` in a loose boolean check. Always compare with `!== false`, or prefer `str_contains()` on PHP 8+ where it's available.
explode() and implode(): splitting and joining

explode($delimiter, $string) splits a string into an array on every occurrence of $delimiter. implode($glue, $array) does the reverse, joining array elements back into a single string. Together they're the standard toolkit for parsing CSV-like text and for rebuilding readable output from a list.

explode-implode.php

PHP
<?php

$csvLine = 'id,name,email';
$columns = explode(',', $csvLine);

print_r($columns);

$rebuilt = implode(' | ', $columns);
echo $rebuilt;
Array
(
    [0] => id
    [1] => name
    [2] => email
)
id | name | email
str_pad() and str_repeat(): padding and repeating

str_pad($string, $length, $padString, $type) pads a string up to a target length, on the left, right, or both sides. str_repeat() simply repeats a string a given number of times. Both are handy for lining up plain-text output, like a CLI table or a fixed-width report.

pad-repeat-example.php

PHP
<?php

echo str_pad('7', 3, '0', STR_PAD_LEFT); // 007
echo PHP_EOL;
echo str_pad('PHP', 10, '.');            // PHP.......
echo PHP_EOL;
echo str_repeat('=', 20);
007
PHP.......
====================

Function

Purpose

strlen()

Number of bytes in a string

strtolower() / strtoupper()

Convert ASCII case

trim() / ltrim() / rtrim()

Strip whitespace (or chosen characters) from ends

str_replace()

Replace all occurrences of a substring

substr()

Extract a slice of a string by position and length

strpos()

Find the offset of a substring, or false if absent

str_contains() (PHP 8+)

Boolean check for whether a substring exists

explode() / implode()

Split a string into an array / join an array into a string

str_pad()

Pad a string to a target length

str_repeat()

Repeat a string a given number of times

  • Most string functions in PHP operate on bytes, not Unicode characters — keep that in mind for non-ASCII text.

  • strpos() can return 0, which is falsy; always check with !== false or switch to str_contains().

  • explode()/implode() are the standard pair for splitting delimited text and rebuilding it.

  • str_pad() is useful for aligning fixed-width text output without a full formatting library.

Tip
When you find yourself chaining several string functions together — trim, then lowercase, then replace — read the chain inside-out from the innermost call. It mirrors the actual order of execution and makes debugging a wrong result much faster than guessing.