Replacing Strings
Swap parts of a string using str_replace().
Syntax
str_replace($search, $replace, $subject);The str_replace() function replaces all occurrences of a search string with a replacement.
Other useful modifiers include trim() to remove whitespace from the ends and substr() to extract part of a string.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Sanitise user input by replacing < and > with HTML entities before rendering.
- Swap a placeholder like {name} inside an email template with the actual customer name.
- Remove all whitespace from a credit card number string before storing it.
More examples
Basic str_replace
str_replace() accepts arrays for both search and replace, swapping multiple placeholders in one call.
<?php
$template = 'Dear {name}, your order {id} is ready.';
$message = str_replace(
['{name}', '{id}'],
['Alice', '4821'],
$template
);
echo $message;Case-insensitive replacement
str_ireplace() performs a case-insensitive search-and-replace, useful for normalising brand names in user content.
<?php
$text = 'PHP is great. php is fun. PHp rocks.';
$result = str_ireplace('php', 'PHP', $text);
echo $result; // PHP is great. PHP is fun. PHP rocks.Using preg_replace for patterns
preg_replace() handles regex patterns, making it suitable for complex replacements that str_replace cannot express.
<?php
$input = ' Hello World ';
// Collapse multiple spaces into one
$result = preg_replace('/\s+/', ' ', trim($input));
echo $result; // Hello World
Discussion