Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

str_replace

Replaces all occurrences of a substring with another string.

Available since: PHP 4

Syntax

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

Parameters

ParameterTypeDescription
$searcharray|stringThe value to look for. Pass an array to search for each of its elements.
$replacearray|stringThe replacement. A string, or an array of replacements matching the $search elements.
$subjectstring|arrayThe string or array of strings to search in.
$countintOptional. This variable receives the number of replacements performed.

Return value

string|arrayA string or an array with the replacements applied.

Examples

A simple replacement:

<?php
 
echo str_replace('world', 'PHP', 'Hello, world!');

Output:

Hello, PHP!

Several replacements in one call:

<?php
 
echo str_replace(['a', 'b'], ['1', '2'], 'abc');

Output:

12c

Counting the replacements:

<?php
 
str_replace('o', '0', 'foo boo', $count);
 
echo $count;

Output:

4

Notes

The function is case-sensitive. Use str_ireplace() for a case-insensitive replacement.

See also

  • str_contains — Checks whether a string contains a given substring.
  • trim — Removes whitespace and other characters from both ends of a string.

Related recipes

In the tutorial

  • Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.

Thanks for reading!

Donate to the site — we work hard for you.