str_replace() Function Use in PHP 8.4 and PHP 8.5

str_replace() works exactly the same in PHP 8.4 and 8.5 as it did in earlier 8.x versions. The core function is stable and unchanged, but there is one important deprecation notice you should be aware of when passing null as the subject.

Usage

The function replaces all occurrences of a search string with a replacement string.

Syntax:

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

Example using str_replace() in PHP 8.4 / 8.5:

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

echo $result;
// Output: Hello PHP
?>

Few More Example

1. Replace in a sentence:

<?php
$sentence = "Hello World, welcome to World of PHP!";
echo str_replace("World", "Universe", $sentence);
// Output: Hello Universe, welcome to Universe of PHP!
?>

2. Replace multiple words using arrays:

<?php
$text = "Hello World";
$search  = ["Hello", "World"];
$replace = ["Namaste", "Duniya"];

echo str_replace($search, $replace, $text);
// Output: Namaste Duniya
?>

11 Views