How to Replace String in PHP - str_replace() Function

The str_replace() function replaces all occurrences of a substring (or an array of substrings) with another substring in a given string.

Syntax

str_replace($search, $replace, $subject)

This function returns a string or an array with the replaced values. To replace text based on a pattern rather than a fixed string, you can use preg_replace().

Parameters

  • $search: The substring to search for. It can be a string or an array of strings.
  • $replace: The replacement substring. It can be a string or an array of strings.
  • $subject: The input string or array of strings to perform the replacement on.

Example

$str = "Hello, World!";
$new_str = str_replace("World", "PHP", $str);
echo $new_str;

Output: Hello, PHP!

Case-Insensitive Replacement

The str_ireplace() function is case-insensitive, meaning it will replace substrings regardless of case.