PHP 8 reference · String Functions

PHP str_replace() Function

Replace every occurrence of a search string with a replacement. Accepts arrays to make several replacements at once.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

str_replace(array|string $search, array|string $replace, string|array $subject, int &$count = null): string|array

Parameters

ParameterDescription
search The value to find, or an array of values.
replace The replacement, or an array matched to search by position.
subject The string (or array of strings) to search in.
count optional Set to the number of replacements made.

Return value

The string (or array) with replacements made.

Examples

Replace textTry it yourself
<?php
echo str_replace("cat", "camel", "The cat sat on the cat mat"), "\n";
echo str_replace(" ", "-", "my blog post title"), "\n";

Output

The camel sat on the camel mat
my-blog-post-title
Several replacementsTry it yourself
<?php
$template = "Hello {name}, your order {id} has shipped.";
echo str_replace(["{name}", "{id}"], ["Ada", "#1042"], $template), "\n";

Output

Hello Ada, your order #1042 has shipped.
Count replacementsTry it yourself
<?php
str_replace("o", "0", "foo boo", $count);
echo $count, "\n";

Output

4

Common mistakes

  • It's case-sensitive; use str_ireplace() to ignore case.
  • With arrays, replacements run in order, so a later rule can change the output of an earlier one. strtr() replaces everything in one pass.

Version history

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?