String search and replace: str_replace, str_ireplace, preg_replace
Concept
PHP's string search-and-replace functions range from simple literal replacement to regex-based transformation. Choosing the right one depends on whether your needle is a literal string or a pattern, whether case matters, and whether you need context from the match.
str_replace($search, $replace, $subject) replaces all occurrences of $search (a string or array of strings) with $replace. Case-sensitive. The array form lets you replace multiple pairs in one call — replacements happen sequentially, so a replacement string can itself be replaced by a later pair. str_ireplace is the case-insensitive variant. Both are O(n·m) where n is string length and m is number of patterns.
str_replace with arrays: both $search and $replace can be arrays of the same length — pairs are replaced in order. This is commonly used for HTML character escaping or slug generation.
preg_replace($pattern, $replacement, $subject) uses PCRE regular expressions. Supports backreferences ($1, \\1) in the replacement. preg_replace_callback passes each match to a callable, enabling complex transformations that can't be expressed as a static replacement string. preg_replace_callback_array maps multiple patterns to different callbacks.
Performance: str_replace is always faster than preg_replace for literal strings — regex has compilation overhead. Use str_replace unless you genuinely need pattern matching.
Code Example
<?php
declare(strict_types=1);
// str_replace — simple literal replacement
$html = '<script>alert("xss")</script>';
$safe = str_replace(['<', '>'], ['<', '>'], $html);
// "<script>alert("xss")</script>"
// Case-insensitive replacement
$text = "Hello WORLD, hello world";
echo str_ireplace('hello', 'Hi', $text); // "Hi WORLD, Hi world"
// Slug generation with array replace
function slugify(string $text): string
{
$text = mb_strtolower($text);
$text = str_replace(
['á','é','í','ó','ú','ñ',' '],
['a','e','i','o','u','n','-'],
$text
);
return preg_replace('/[^a-z0-9-]/', '', $text);
}
echo slugify('Héllo Wörld!'); // "hello-world"
// preg_replace — pattern-based replacement
$phone = '(555) 123-4567';
$digits = preg_replace('/\D/', '', $phone); // "5551234567"
// Backreferences in replacement
$date = '2024-01-15';
echo preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3/$2/$1', $date);
// "15/01/2024"
// preg_replace_callback — complex transformations
$template = 'Hello {name}, you have {count} messages';
$vars = ['name' => 'Codrut', 'count' => '5'];
$result = preg_replace_callback(
'/\{(\w+)\}/',
fn(array $m) => $vars[$m[1]] ?? $m[0],
$template
);
echo $result; // "Hello Codrut, you have 5 messages"
// preg_replace with limit
$text = "aaa bbb aaa ccc aaa";
echo preg_replace('/aaa/', 'XXX', $text, 2); // "XXX bbb XXX ccc aaa"