Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

PHP Dictionary

  1. Home
  2. PHP Dictionary
  3. str_replace() / str_ireplace()

str_replace() / str_ireplace() Since: PHP 4(2000)

Replaces all occurrences of a specified string within a string with another string. To replace without case sensitivity, use str_ireplace().

Syntax

// Replaces all matching occurrences.
str_replace($search, $replace, $subject, &$count);

// Replaces without distinguishing uppercase and lowercase.
str_ireplace($search, $replace, $subject, &$count);

Functions

FunctionDescription
str_replace($search, $replace, $subject)Returns a string with all occurrences of $search in $subject replaced with $replace. Case-sensitive.
str_ireplace($search, $replace, $subject)Replaces without case sensitivity. All other behavior is the same as str_replace().

Return Value

Returns the string after replacement. If you pass a variable as the fourth argument, it will hold the number of replacements made.

Sample Code

<?php
// Basic string replacement.
$str = "apple and orange and apple";
echo str_replace("apple", "grape", $str); // Outputs: "grape and orange and grape"

// Pass arrays to replace multiple strings at once.
$template = "Dear {{Name}}, your order number is {{OrderNumber}}.";
$search = ["{{Name}}", "{{OrderNumber}}"];
$replace = ["John Smith", "A-12345"];
echo str_replace($search, $replace, $template); // Outputs: "Dear John Smith, your order number is A-12345."

// Use the fourth argument to get the replacement count.
$count = 0;
$result = str_replace("PHP", "Python", "PHP is fun. PHP is useful.", $count);
echo $result; // Outputs: "Python is fun. Python is useful."
echo $count; // Outputs: 2

// str_ireplace() is case-insensitive.
echo str_ireplace("hello", "Hi", "Hello HELLO hello"); // Outputs: "Hi Hi Hi"

// Replacing with an empty string removes the matched parts.
$html = "This is bold text.";
echo str_replace(["", ""], "", $html); // Outputs: "This is bold text."

// Normalizing line endings.
$text = "Line1\r\nLine2\rLine3\nLine4";
$unified = str_replace(["\r\n", "\r"], "\n", $text); // All line endings are unified to LF.

Notes

str_replace() replaces all occurrences of a specified substring within a string. By passing arrays for both the search and replace arguments, you can perform multiple replacements in one call. When using arrays, replacements are applied from left to right, so an earlier replacement may affect a subsequent one — keep this in mind.

str_ireplace() is the case-insensitive version. It is useful when processing strings that mix uppercase and lowercase, such as HTML tags or keywords.

For advanced replacements using regular expressions, use preg_replace(). To search within a string, use strpos(). To split a string, use explode().

If you find any errors or copyright issues, please .