Web Analytics

PHP str_replace() Function

String Function PHP 4+

The str_replace() function replaces all occurrences of a search string (or array of strings) with a replacement string (or array).

Syntax

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

Parameters

Parameter Type Description
$search string|array The value(s) to search for
$replace string|array The replacement value(s)
$subject string|array The string or array to search in
$count int Optional. Number of replacements performed

Return Value

Returns a string or array with all occurrences of search replaced with replace.

Try It Online

Output
Click Run to execute your code

More Examples

Simple Replace

<?php
$text = "Hello World";
$result = str_replace("World", "PHP", $text);
echo $result;  // "Hello PHP"
?>

Multiple Replacements

<?php
$text = "I like apples and apples are healthy";
$result = str_replace(
    ["apples", "healthy"],
    ["oranges", "delicious"],
    $text
);
echo $result;
// "I like oranges and oranges are delicious"
?>

Count Replacements

<?php
$text = "PHP is great. PHP is powerful.";
$count = 0;
$result = str_replace("PHP", "Python", $text, $count);
echo "Made $count replacements\n";  // Made 2 replacements
echo $result;
?>
Tip: For case-insensitive replacements, use str_ireplace() instead.

Common Use Cases

  • Template variable replacement
  • Sanitizing user input
  • URL slug generation
  • Text formatting

Related Functions

  • str_ireplace() - Case-insensitive version
  • substr() - Extract part of a string
  • strpos() - Find position of substring
  • preg_replace() - Regex-based replacement